예제 #1
0
 /**
  * {@inheritdoc}
  */
 public function run()
 {
     $settingsPath = DRUPAL_ROOT . '/' . DrupalKernel::findSitePath(Drupal::request()) . '/settings.php';
     $result = CheckResult::FAIL;
     $findings = array();
     if (file_exists($settingsPath)) {
         if ($this->settings()->get('method', 'token') === 'token') {
             $content = file_get_contents($settingsPath);
             $tokens = token_get_all($content);
             foreach ($tokens as $token) {
                 if (is_array($token) && $token[0] === T_VARIABLE && $token[1] == '$base_url') {
                     $result = CheckResult::SUCCESS;
                     break;
                 }
             }
         } else {
             include $settingsPath;
             if (isset($base_url)) {
                 $result = CheckResult::SUCCESS;
             }
         }
         global $base_url;
         if ($result === CheckResult::FAIL) {
             $findings[] = t('Your site is available at the following URL: !url.', array('!url' => $base_url));
             $findings[] = t("If your site should only be available at that URL it is recommended that you set it as the \$base_url variable in the settings.php file at !file", array('!file' => $settingsPath));
             $findings[] = t("Or, if you are using Drupal's multi-site functionality then you should set the \$base_url variable for the appropriate settings.php for your site.");
         }
         return $this->createResult($result, $findings);
     } else {
         return $this->createResult(CheckResult::INFO, array(t("Couldn't determine settings.php's path.")));
     }
 }
예제 #2
0
 function setUp()
 {
     parent::setUp();
     // Add file_private_path setting.
     $request = Request::create('/');
     $site_path = DrupalKernel::findSitePath($request);
     $this->setSetting('file_private_path', $site_path . '/private');
 }
 function setUp()
 {
     // Add file_private_path setting.
     $settings = Settings::getAll();
     $request = Request::create('/');
     $site_path = DrupalKernel::findSitePath($request);
     $settings['file_private_path'] = $site_path . '/private';
     new Settings($settings + Settings::getAll());
     parent::setUp();
 }
 /**
  * {@inheritdoc}
  *
  * Configures a preexisting settings.php file without an install_profile
  * setting before invoking the interactive installer.
  */
 protected function setUp()
 {
     // Pre-configure hash salt.
     // Any string is valid, so simply use the class name of this test.
     $this->settings['settings']['hash_salt'] = (object) array('value' => __CLASS__, 'required' => TRUE);
     // Pre-configure database credentials.
     $connection_info = Database::getConnectionInfo();
     unset($connection_info['default']['pdo']);
     unset($connection_info['default']['init_commands']);
     $this->settings['databases']['default'] = (object) array('value' => $connection_info, 'required' => TRUE);
     // Pre-configure config directories.
     $this->settings['config_directories'] = array(CONFIG_SYNC_DIRECTORY => (object) array('value' => DrupalKernel::findSitePath(Request::createFromGlobals()) . '/files/config_sync', 'required' => TRUE));
     mkdir($this->settings['config_directories'][CONFIG_SYNC_DIRECTORY]->value, 0777, TRUE);
     parent::setUp();
 }
예제 #5
0
        /**
         * Tests site path finding.
         *
         * This test is run in a separate process since it defines DRUPAL_ROOT. This
         * stops any possible pollution of other tests.
         *
         * @covers ::findSitePath
         * @runInSeparateProcess
         */
        public function testFindSitePath()
        {
            $vfs_root = vfsStream::setup('drupal_root');
            $sites_php = <<<'EOD'
<?php
$sites['8888.www.example.org'] = 'example';
EOD;
            // Create the expected directory structure.
            vfsStream::create(['sites' => ['sites.php' => $sites_php, 'example' => ['settings.php' => 'test']]]);
            define('DRUPAL_ROOT', $vfs_root->url('drupal_root'));
            $request = new Request();
            $request->server->set('SERVER_NAME', 'www.example.org');
            $request->server->set('SERVER_PORT', '8888');
            $request->server->set('SCRIPT_NAME', '/index.php');
            $this->assertEquals('sites/example', DrupalKernel::findSitePath($request));
        }
예제 #6
0
 function conf_path($require_settings = TRUE, $reset = FALSE, Request $request = NULL)
 {
     if (!isset($request)) {
         if (\Drupal::hasRequest()) {
             $request = \Drupal::request();
         } else {
             $request = Request::createFromGlobals();
         }
     }
     if (\Drupal::hasService('kernel')) {
         $site_path = \Drupal::service('kernel')->getSitePath();
     }
     if (!isset($site_path) || empty($site_path)) {
         $site_path = DrupalKernel::findSitePath($request, $require_settings);
     }
     return $site_path;
 }
예제 #7
0
 /**
  * Create a Drupal application.
  */
 public function getApplication()
 {
     // Bootstrap Drupal.
     // Bootstrap code is modeled on a few examples in core/scripts, such as
     // db-tools.php.
     // Assume we're in DRUPAL_ROOT/vendor/php-pm/httpkernel-adapter/Bootstraps.
     // There may be a safer way to do this...
     $drupal_root = dirname(dirname(dirname(dirname(__DIR__))));
     // @todo: Is it necessary to call bootEnv()?  It's called automatically by createFromRequest().
     DrupalKernel::bootEnvironment();
     $request = Request::createFromGlobals();
     // @todo: Is it necessary to call initialize()? Is it called through createFromRequest()?
     $autoloader = (include $drupal_root . '/autoload.php');
     Settings::initialize($drupal_root, DrupalKernel::findSitePath($request), $autoloader);
     $app = DrupalKernel::createFromRequest($request, $autoloader, $this->appenv);
     $app->boot();
     return $app;
 }
 /**
  * Overrides method.
  *
  * We have several forms to navigate through.
  */
 protected function setUpSite()
 {
     // Recreate the container so that we can simulate the submission of the
     // SyncConfigureForm after the full bootstrap has occurred. Without out this
     // drupal_realpath() does not work so uploading files through
     // WebTestBase::postForm() is impossible.
     $request = Request::createFromGlobals();
     $class_loader = (require $this->container->get('app.root') . '/vendor/autoload.php');
     Settings::initialize($this->container->get('app.root'), DrupalKernel::findSitePath($request), $class_loader);
     foreach ($GLOBALS['config_directories'] as $type => $path) {
         $this->configDirectories[$type] = $path;
     }
     $this->kernel = DrupalKernel::createFromRequest($request, $class_loader, 'prod', FALSE);
     $this->kernel->prepareLegacyRequest($request);
     $this->container = $this->kernel->getContainer();
     $this->setUpSyncForm();
     $this->setUpInstallConfigureForm();
     // If we've got to this point the site is installed using the regular
     // installation workflow.
     $this->isInstalled = TRUE;
 }
예제 #9
0
 protected function setUp()
 {
     parent::setUp();
     // Change the root path which Update Manager uses to install and update
     // projects to be inside the testing site directory. See
     // \Drupal\update\UpdateRootFactory::get() for equivalent changes to the
     // test child site.
     $request = \Drupal::request();
     $update_root = $this->container->get('update.root') . '/' . DrupalKernel::findSitePath($request);
     $this->container->set('update.root', $update_root);
     \Drupal::setContainer($this->container);
     // Create the directories within the root path within which the Update
     // Manager will install projects.
     foreach (drupal_get_updaters() as $updater_info) {
         $updater = $updater_info['class'];
         $install_directory = $update_root . '/' . $updater::getRootDirectoryRelativePath();
         if (!is_dir($install_directory)) {
             mkdir($install_directory);
         }
     }
 }
 /**
  * {@inheritdoc}
  *
  * Fully configures a preexisting settings.php file before invoking the
  * interactive installer.
  */
 protected function setUp()
 {
     // Pre-configure hash salt.
     // Any string is valid, so simply use the class name of this test.
     $this->settings['settings']['hash_salt'] = (object) array('value' => __CLASS__, 'required' => TRUE);
     // During interactive install we'll change this to a different profile and
     // this test will ensure that the new value is written to settings.php.
     $this->settings['settings']['install_profile'] = (object) array('value' => 'minimal', 'required' => TRUE);
     // Pre-configure database credentials.
     $connection_info = Database::getConnectionInfo();
     unset($connection_info['default']['pdo']);
     unset($connection_info['default']['init_commands']);
     $this->settings['databases']['default'] = (object) array('value' => $connection_info, 'required' => TRUE);
     // Use the kernel to find the site path because the site.path service should
     // not be available at this point in the install process.
     $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
     // Pre-configure config directories.
     $this->settings['config_directories'] = array(CONFIG_SYNC_DIRECTORY => (object) array('value' => $site_path . '/files/config_sync', 'required' => TRUE));
     mkdir($this->settings['config_directories'][CONFIG_SYNC_DIRECTORY]->value, 0777, TRUE);
     parent::setUp();
 }
예제 #11
0
 /**
  * @param $migration
  *
  * @return array
  */
 public function exclude($migration)
 {
     $exclude = array('.', '..', '.git', '.svn', 'CVS', '.bzr');
     // Exclude the migration directory.
     $exclude[] = basename($migration['dir']);
     if (!\Drupal::config('acquia_connector.settings')->get('migrate.files')) {
         $exclude[] = \Drupal::service('file_system')->realpath(DrupalKernel::findSitePath(\Drupal::request()) . DIRECTORY_SEPARATOR . 'files');
     }
     return $exclude;
 }
예제 #12
0
<?php

/**
 * @file
 * Rebuilds all Drupal caches even when Drupal itself does not work.
 *
 * Needs a token query argument which can be calculated using the
 * scripts/rebuild_token_calculator.sh script.
 *
 * @see drupal_rebuild()
 */
use Drupal\Component\Utility\Crypt;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
// Change the directory to the Drupal root.
chdir('..');
$autoloader = (require_once __DIR__ . '/vendor/autoload.php');
require_once __DIR__ . '/includes/utility.inc';
$request = Request::createFromGlobals();
// Manually resemble early bootstrap of DrupalKernel::boot().
require_once __DIR__ . '/includes/bootstrap.inc';
DrupalKernel::bootEnvironment();
Settings::initialize(DrupalKernel::findSitePath($request), $autoloader);
if (Settings::get('rebuild_access', FALSE) || $request->get('token') && $request->get('timestamp') && REQUEST_TIME - $request->get('timestamp') < 300 && $request->get('token') === Crypt::hmacBase64($request->get('timestamp'), Settings::get('hash_salt'))) {
    drupal_rebuild($autoloader, $request);
    drupal_set_message('Cache rebuild complete.');
}
$base_path = dirname(dirname($request->getBaseUrl()));
header('Location: ' . $base_path);
예제 #13
0
 /**
  * {@inheritdoc}
  */
 public function validateDrupalSite()
 {
     if ('default' !== $this->uri) {
         // Fake the necessary HTTP headers that Drupal needs:
         $drupal_base_url = parse_url($this->uri);
         // If there's no url scheme set, add http:// and re-parse the url
         // so the host and path values are set accurately.
         if (!array_key_exists('scheme', $drupal_base_url)) {
             $drupal_base_url = parse_url($this->uri);
         }
         // Fill in defaults.
         $drupal_base_url += array('path' => NULL, 'host' => NULL, 'port' => NULL);
         $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
         if ($drupal_base_url['port']) {
             $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
         }
         $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
         if (array_key_exists('path', $drupal_base_url)) {
             $_SERVER['PHP_SELF'] = $drupal_base_url['path'] . '/index.php';
         } else {
             $_SERVER['PHP_SELF'] = '/index.php';
         }
     } else {
         $_SERVER['HTTP_HOST'] = 'default';
         $_SERVER['PHP_SELF'] = '/index.php';
     }
     $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     $_SERVER['REQUEST_METHOD'] = NULL;
     $_SERVER['SERVER_SOFTWARE'] = NULL;
     $_SERVER['HTTP_USER_AGENT'] = NULL;
     $conf_path = DrupalKernel::findSitePath(Request::createFromGlobals());
     $conf_file = $this->drupalRoot . "/{$conf_path}/settings.php";
     if (!file_exists($conf_file)) {
         throw new BootstrapException(sprintf('Could not find a Drupal settings.php file at "%s"', $conf_file));
     }
 }
 /**
  * Overrides WebTestBase::setUp().
  */
 protected function setUp()
 {
     $this->isInstalled = FALSE;
     // Define information about the user 1 account.
     $this->root_user = new UserSession(array('uid' => 1, 'name' => 'admin', 'mail' => '*****@*****.**', 'pass_raw' => $this->randomMachineName()));
     // If any $settings are defined for this test, copy and prepare an actual
     // settings.php, so as to resemble a regular installation.
     if (!empty($this->settings)) {
         // Not using File API; a potential error must trigger a PHP warning.
         copy(DRUPAL_ROOT . '/sites/default/default.settings.php', DRUPAL_ROOT . '/' . $this->siteDirectory . '/settings.php');
         $this->writeSettings($this->settings);
     }
     // Note that WebTestBase::installParameters() returns form input values
     // suitable for a programmed drupal_form_submit().
     // @see WebTestBase::translatePostValues()
     $this->parameters = $this->installParameters();
     // Set up a minimal container (required by WebTestBase).
     // @see install_begin_request()
     $request = Request::create($GLOBALS['base_url'] . '/core/install.php');
     $this->container = new ContainerBuilder();
     $request_stack = new RequestStack();
     $request_stack->push($request);
     $this->container->set('request_stack', $request_stack);
     $this->container->setParameter('language.default_values', Language::$defaultValues);
     $this->container->register('language.default', 'Drupal\\Core\\Language\\LanguageDefault')->addArgument('%language.default_values%');
     $this->container->register('language_manager', 'Drupal\\Core\\Language\\LanguageManager')->addArgument(new Reference('language.default'));
     $this->container->register('string_translation', 'Drupal\\Core\\StringTranslation\\TranslationManager')->addArgument(new Reference('language_manager'));
     \Drupal::setContainer($this->container);
     $this->drupalGet($GLOBALS['base_url'] . '/core/install.php');
     // Select language.
     $this->setUpLanguage();
     // Select profile.
     $this->setUpProfile();
     // Configure settings.
     $this->setUpSettings();
     // @todo Allow test classes based on this class to act on further installer
     //   screens.
     // Configure site.
     $this->setUpSite();
     // Import new settings.php written by the installer.
     $request = Request::createFromGlobals();
     $class_loader = (require DRUPAL_ROOT . '/core/vendor/autoload.php');
     Settings::initialize(DrupalKernel::findSitePath($request), $class_loader);
     foreach ($GLOBALS['config_directories'] as $type => $path) {
         $this->configDirectories[$type] = $path;
     }
     // After writing settings.php, the installer removes write permissions
     // from the site directory. To allow drupal_generate_test_ua() to write
     // a file containing the private key for drupal_valid_test_ua(), the site
     // directory has to be writable.
     // WebTestBase::tearDown() will delete the entire test site directory.
     // Not using File API; a potential error must trigger a PHP warning.
     chmod(DRUPAL_ROOT . '/' . $this->siteDirectory, 0777);
     $this->kernel = DrupalKernel::createFromRequest($request, $class_loader, 'prod', FALSE);
     $this->kernel->prepareLegacyRequest($request);
     $this->container = $this->kernel->getContainer();
     $config = $this->container->get('config.factory');
     // Manually configure the test mail collector implementation to prevent
     // tests from sending out e-mails and collect them in state instead.
     $config->get('system.mail')->set('interface.default', 'test_mail_collector')->save();
     // When running from run-tests.sh we don't get an empty current path which
     // would indicate we're on the home page.
     $path = current_path();
     if (empty($path)) {
         _current_path('run-tests');
     }
     $this->isInstalled = TRUE;
 }
예제 #15
0
 /**
  * Discovers available extensions of a given type.
  *
  * Finds all extensions (modules, themes, etc) that exist on the site. It
  * searches in several locations. For instance, to discover all available
  * modules:
  * @code
  * $listing = new ExtensionDiscovery(\Drupal::root());
  * $modules = $listing->scan('module');
  * @endcode
  *
  * The following directories will be searched (in the order stated):
  * - the core directory; i.e., /core
  * - the installation profile directory; e.g., /core/profiles/standard
  * - the legacy site-wide directory; i.e., /sites/all
  * - the site-wide directory; i.e., /
  * - the site-specific directory; e.g., /sites/example.com
  *
  * The information is returned in an associative array, keyed by the extension
  * name (without .info.yml extension). Extensions found later in the search
  * will take precedence over extensions found earlier - unless they are not
  * compatible with the current version of Drupal core.
  *
  * @param string $type
  *   The extension type to search for. One of 'profile', 'module', 'theme', or
  *   'theme_engine'.
  * @param bool $include_tests
  *   (optional) Whether to explicitly include or exclude test extensions. By
  *   default, test extensions are only discovered when in a test environment.
  *
  * @return \Drupal\Core\Extension\Extension[]
  *   An associative array of Extension objects, keyed by extension name.
  */
 public function scan($type, $include_tests = NULL)
 {
     // Determine the installation profile directories to scan for extensions,
     // unless explicit profile directories have been set. Exclude profiles as we
     // cannot have profiles within profiles.
     if (!isset($this->profileDirectories) && $type != 'profile') {
         $this->setProfileDirectoriesFromSettings();
     }
     // Search the core directory.
     $searchdirs[static::ORIGIN_CORE] = 'core';
     // Search the legacy sites/all directory.
     $searchdirs[static::ORIGIN_SITES_ALL] = 'sites/all';
     // Search for contributed and custom extensions in top-level directories.
     // The scan uses a whitelist to limit recursion to the expected extension
     // type specific directory names only.
     $searchdirs[static::ORIGIN_ROOT] = '';
     // Simpletest uses the regular built-in multi-site functionality of Drupal
     // for running web tests. As a consequence, extensions of the parent site
     // located in a different site-specific directory are not discovered in a
     // test site environment, because the site directories are not the same.
     // Therefore, add the site directory of the parent site to the search paths,
     // so that contained extensions are still discovered.
     // @see \Drupal\simpletest\WebTestBase::setUp()
     if ($parent_site = Settings::get('test_parent_site')) {
         $searchdirs[static::ORIGIN_PARENT_SITE] = $parent_site;
     }
     // Find the site-specific directory to search. Since we are using this
     // method to discover extensions including profiles, we might be doing this
     // at install time. Therefore Kernel service is not always available, but is
     // preferred.
     if (\Drupal::hasService('kernel')) {
         $searchdirs[static::ORIGIN_SITE] = \Drupal::service('site.path');
     } else {
         $searchdirs[static::ORIGIN_SITE] = $this->sitePath ?: DrupalKernel::findSitePath(Request::createFromGlobals());
     }
     // Unless an explicit value has been passed, manually check whether we are
     // in a test environment, in which case test extensions must be included.
     // Test extensions can also be included for debugging purposes by setting a
     // variable in settings.php.
     if (!isset($include_tests)) {
         $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
     }
     $files = array();
     foreach ($searchdirs as $dir) {
         // Discover all extensions in the directory, unless we did already.
         if (!isset(static::$files[$dir][$include_tests])) {
             static::$files[$dir][$include_tests] = $this->scanDirectory($dir, $include_tests);
         }
         // Only return extensions of the requested type.
         if (isset(static::$files[$dir][$include_tests][$type])) {
             $files += static::$files[$dir][$include_tests][$type];
         }
     }
     // If applicable, filter out extensions that do not belong to the current
     // installation profiles.
     $files = $this->filterByProfileDirectories($files);
     // Sort the discovered extensions by their originating directories.
     $origin_weights = array_flip($searchdirs);
     $files = $this->sort($files, $origin_weights);
     // Process and return the list of extensions keyed by extension name.
     return $this->process($files);
 }
예제 #16
0
    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->keyValueFactory = new KeyValueMemoryFactory();
        // Back up settings from TestBase::prepareEnvironment().
        $settings = Settings::getAll();
        // Allow for test-specific overrides.
        $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
        $settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
        $container_yamls = [];
        if (file_exists($settings_services_file)) {
            // Copy the testing-specific service overrides in place.
            $testing_services_file = $directory . '/services.yml';
            copy($settings_services_file, $testing_services_file);
            $container_yamls[] = $testing_services_file;
        }
        $settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSite . '/settings.testing.php';
        if (file_exists($settings_testing_file)) {
            // Copy the testing-specific settings.php overrides in place.
            copy($settings_testing_file, $directory . '/settings.testing.php');
        }
        if (file_exists($directory . '/settings.testing.php')) {
            // Add the name of the testing class to settings.php and include the
            // testing specific overrides
            $hash_salt = Settings::getHashSalt();
            $test_class = get_class($this);
            $container_yamls_export = Variable::export($container_yamls);
            $php = <<<EOD
<?php

\$settings['hash_salt'] = '{$hash_salt}';
\$settings['container_yamls'] = {$container_yamls_export};

\$test_class = '{$test_class}';
include DRUPAL_ROOT . '/' . \$site_path . '/settings.testing.php';
EOD;
            file_put_contents($directory . '/settings.php', $php);
        }
        // Add this test class as a service provider.
        // @todo Remove the indirection; implement ServiceProviderInterface instead.
        $GLOBALS['conf']['container_service_providers']['TestServiceProvider'] = 'Drupal\\simpletest\\TestServiceProvider';
        // Bootstrap a new kernel.
        $class_loader = (require DRUPAL_ROOT . '/autoload.php');
        $this->kernel = new DrupalKernel('testing', $class_loader, FALSE);
        $request = Request::create('/');
        $site_path = DrupalKernel::findSitePath($request);
        $this->kernel->setSitePath($site_path);
        if (file_exists($directory . '/settings.testing.php')) {
            Settings::initialize(DRUPAL_ROOT, $site_path, $class_loader);
        }
        $this->kernel->boot();
        // Ensure database install tasks have been run.
        require_once __DIR__ . '/../../../includes/install.inc';
        $connection = Database::getConnection();
        $errors = db_installer_object($connection->driver())->runTasks();
        if (!empty($errors)) {
            $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
        }
        // Reboot the kernel because the container might contain a connection to the
        // database that has been closed during the database install tasks. This
        // prevents any services created during the first boot from having stale
        // database connections, for example, \Drupal\Core\Config\DatabaseStorage.
        $this->kernel->shutdown();
        $this->kernel->boot();
        // Save the original site directory path, so that extensions in the
        // site-specific directory can still be discovered in the test site
        // environment.
        // @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
        $settings['test_parent_site'] = $this->originalSite;
        // Restore and merge settings.
        // DrupalKernel::boot() initializes new Settings, and the containerBuild()
        // method sets additional settings.
        new Settings($settings + Settings::getAll());
        // Create and set new configuration directories.
        $this->prepareConfigDirectories();
        // Set the request scope.
        $this->container = $this->kernel->getContainer();
        $this->container->get('request_stack')->push($request);
        // Re-inject extension file listings into state, unless the key/value
        // service was overridden (in which case its storage does not exist yet).
        if ($this->container->get('keyvalue') instanceof KeyValueMemoryFactory) {
            $this->container->get('state')->set('system.module.files', $this->moduleFiles);
            $this->container->get('state')->set('system.theme.files', $this->themeFiles);
        }
        // Create a minimal core.extension configuration object so that the list of
        // enabled modules can be maintained allowing
        // \Drupal\Core\Config\ConfigInstaller::installDefaultConfig() to work.
        // Write directly to active storage to avoid early instantiation of
        // the event dispatcher which can prevent modules from registering events.
        \Drupal::service('config.storage')->write('core.extension', array('module' => array(), 'theme' => array()));
        // Collect and set a fixed module list.
        $class = get_class($this);
        $modules = array();
        while ($class) {
            if (property_exists($class, 'modules')) {
                // Only add the modules, if the $modules property was not inherited.
                $rp = new \ReflectionProperty($class, 'modules');
                if ($rp->class == $class) {
                    $modules[$class] = $class::$modules;
                }
            }
            $class = get_parent_class($class);
        }
        // Modules have been collected in reverse class hierarchy order; modules
        // defined by base classes should be sorted first. Then, merge the results
        // together.
        $modules = array_reverse($modules);
        $modules = call_user_func_array('array_merge_recursive', $modules);
        if ($modules) {
            $this->enableModules($modules);
        }
        // Tests based on this class are entitled to use Drupal's File and
        // StreamWrapper APIs.
        // @todo Move StreamWrapper management into DrupalKernel.
        // @see https://www.drupal.org/node/2028109
        file_prepare_directory($this->publicFilesDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
        $this->settingsSet('file_public_path', $this->publicFilesDirectory);
        $this->streamWrappers = array();
        $this->registerStreamWrapper('public', 'Drupal\\Core\\StreamWrapper\\PublicStream');
        // The temporary stream wrapper is able to operate both with and without
        // configuration.
        $this->registerStreamWrapper('temporary', 'Drupal\\Core\\StreamWrapper\\TemporaryStream');
    }
예제 #17
0
<?php

/**
 * @file
 * Rebuilds all Drupal caches even when Drupal itself does not work.
 *
 * Needs a token query argument which can be calculated using the
 * scripts/rebuild_token_calculator.sh script.
 *
 * @see drupal_rebuild()
 */
use Drupal\Component\Utility\Crypt;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
// Change the directory to the Drupal root.
chdir('..');
$autoloader = (require_once __DIR__ . '/vendor/autoload.php');
require_once __DIR__ . '/includes/utility.inc';
$request = Request::createFromGlobals();
// Manually resemble early bootstrap of DrupalKernel::boot().
require_once __DIR__ . '/includes/bootstrap.inc';
DrupalKernel::bootEnvironment();
Settings::initialize(DrupalKernel::findSitePath($request));
if (Settings::get('rebuild_access', FALSE) || $request->get('token') && $request->get('timestamp') && REQUEST_TIME - $request->get('timestamp') < 300 && $request->get('token') === Crypt::hmacBase64($request->get('timestamp'), Settings::get('hash_salt'))) {
    drupal_rebuild($autoloader, $request);
    drupal_set_message('Cache rebuild complete.');
}
$base_path = dirname(dirname($request->getBaseUrl()));
header('Location: ' . $base_path);
예제 #18
0
 /**
  * @Todo: Remove when issue https://www.drupal.org/node/2556025 get resolved
  *
  * Rebuilds all caches even when Drupal itself does not work.
  *
  * @param \Composer\Autoload\ClassLoader $class_loader
  *   The class loader.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request.
  *
  * @see rebuild.php
  */
 public function drupal_rebuild($class_loader, \Symfony\Component\HttpFoundation\Request $request)
 {
     // Remove Drupal's error and exception handlers; they rely on a working
     // service container and other subsystems and will only cause a fatal error
     // that hides the actual error.
     restore_error_handler();
     restore_exception_handler();
     // Force kernel to rebuild php cache.
     \Drupal\Core\PhpStorage\PhpStorageFactory::get('twig')->deleteAll();
     // Bootstrap up to where caches exist and clear them.
     $kernel = new \Drupal\Core\DrupalKernel('prod', $class_loader);
     $kernel->setSitePath(\Drupal\Core\DrupalKernel::findSitePath($request));
     // Invalidate the container.
     $kernel->invalidateContainer();
     // Prepare a NULL request.
     $kernel->prepareLegacyRequest($request);
     foreach (Cache::getBins() as $bin) {
         $bin->deleteAll();
     }
     // Disable recording of cached pages.
     \Drupal::service('page_cache_kill_switch')->trigger();
     drupal_flush_all_caches();
     // Restore Drupal's error and exception handlers.
     // @see \Drupal\Core\DrupalKernel::boot()
     set_error_handler('_drupal_error_handler');
     set_exception_handler('_drupal_exception_handler');
 }
예제 #19
0
 /**
  * Returns the base path for public://.
  *
  * If we have a setting for the public:// scheme's path, we use that.
  * Otherwise we build a reasonable default based on the site.path service if
  * it's available, or a default behavior based on the request.
  *
  * Note that this static method is used by \Drupal\system\Form\FileSystemForm
  * so you should alter that form or substitute a different form if you change
  * the class providing the stream_wrapper.public service.
  *
  * The site path is injectable from the site.path service:
  * @code
  * $base_path = PublicStream::basePath(\Drupal::service('site.path'));
  * @endcode
  *
  * @param \SplString $site_path
  *   (optional) The site.path service parameter, which is typically the path
  *   to sites/ in a Drupal installation. This allows you to inject the site
  *   path using services from the caller. If omitted, this method will use the
  *   global service container or the kernel's default behavior to determine
  *   the site path.
  *
  * @return string
  *   The base path for public:// typically sites/default/files.
  */
 public static function basePath(\SplString $site_path = NULL)
 {
     if ($site_path === NULL) {
         // Find the site path. Kernel service is not always available at this
         // point, but is preferred, when available.
         if (\Drupal::hasService('kernel')) {
             $site_path = \Drupal::service('site.path');
         } else {
             // If there is no kernel available yet, we call the static
             // findSitePath().
             $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
         }
     }
     return Settings::get('file_public_path', $site_path . '/files');
 }
예제 #20
0
 /**
  * Determines if settings.php is read-only
  *
  * @return boolean
  */
 private function getSettingsPermissions()
 {
     $settings_permissions_read_only = TRUE;
     $writes = array('2', '3', '6', '7');
     // http://en.wikipedia.org/wiki/File_system_permissions
     $settings_file = './' . DrupalKernel::findSitePath(\Drupal::request(), TRUE) . '/settings.php';
     $permissions = Unicode::substr(sprintf('%o', fileperms($settings_file)), -4);
     foreach ($writes as $bit) {
         if (strpos($permissions, $bit)) {
             $settings_permissions_read_only = FALSE;
             break;
         }
     }
     return $settings_permissions_read_only;
 }
 /**
  * Check if PHP files written to the files directory can be executed.
  */
 private function checkExecutablePHP($last_check = NULL)
 {
     global $base_url;
     $result = TRUE;
     $check_result_value = array();
     $message = 'Security review test ' . date('Ymdhis');
     $content = "<?php\necho '" . $message . "';";
     $directory = Settings::get('file_public_path');
     if (empty($directory)) {
         $directory = DrupalKernel::findSitePath(\Drupal::request()) . DIRECTORY_SEPARATOR . 'files';
     }
     if (empty($directory)) {
         $directory = 'sites/default/files';
     }
     $file = '/security_review_test.php';
     if ($file_create = @fopen('./' . $directory . $file, 'w')) {
         $create_status = fwrite($file_create, $content);
         fclose($file_create);
     }
     try {
         $response = \Drupal::httpClient()->post($base_url . '/' . $directory . $file);
         if ($response->getStatusCode() == 200 && $response->getBody()->read(100) === $message) {
             $result = FALSE;
             $check_result_value[] = 'executable_php';
         }
     } catch (\Exception $e) {
         $response = $e->getResponse();
     }
     if (file_exists('./' . $directory . $file)) {
         @unlink('./' . $directory . $file);
     }
     // Check for presence of the .htaccess file and if the contents are correct.
     if (!file_exists($directory . '/.htaccess')) {
         $result = FALSE;
         $check_result_value[] = 'missing_htaccess';
     } elseif (!function_exists('file_htaccess_lines')) {
         $result = FALSE;
         $check_result_value[] = 'outdated_core';
     } else {
         $contents = file_get_contents($directory . '/.htaccess');
         // Text from includes/file.inc.
         $expected = file_htaccess_lines(FALSE);
         if ($contents !== $expected) {
             $result = FALSE;
             $check_result_value[] = 'incorrect_htaccess';
         }
         if (is_writable($directory . '/.htaccess')) {
             // Don't modify $result.
             $check_result_value[] = 'writable_htaccess';
         }
     }
     return array('result' => $result, 'value' => $check_result_value);
 }
예제 #22
0
#!/usr/bin/env php
<?php 
use Drupal\Core\Command\DbDumpApplication;
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
if (PHP_SAPI !== 'cli') {
    return;
}
// Bootstrap.
$autoloader = (require __DIR__ . '/../../autoload.php');
require_once __DIR__ . '/../includes/bootstrap.inc';
$request = Request::createFromGlobals();
Settings::initialize(dirname(dirname(__DIR__)), DrupalKernel::findSitePath($request), $autoloader);
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod')->boot();
// Run the database dump command.
$application = new DbDumpApplication(Database::getConnection(), \Drupal::moduleHandler());
$application->run();
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $this->keyValueFactory = new KeyValueMemoryFactory();
     // Allow for test-specific overrides.
     $settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
     if (file_exists($settings_services_file)) {
         // Copy the testing-specific service overrides in place.
         copy($settings_services_file, DRUPAL_ROOT . '/' . $this->siteDirectory . '/services.yml');
     }
     // Create and set new configuration directories.
     $this->prepareConfigDirectories();
     // Add this test class as a service provider.
     // @todo Remove the indirection; implement ServiceProviderInterface instead.
     $GLOBALS['conf']['container_service_providers']['TestServiceProvider'] = 'Drupal\\simpletest\\TestServiceProvider';
     // Back up settings from TestBase::prepareEnvironment().
     $settings = Settings::getAll();
     // Bootstrap a new kernel. Don't use createFromRequest so we don't mess with settings.
     $class_loader = (require DRUPAL_ROOT . '/core/vendor/autoload.php');
     $this->kernel = new DrupalKernel('testing', $class_loader, FALSE);
     $request = Request::create('/');
     $this->kernel->setSitePath(DrupalKernel::findSitePath($request));
     $this->kernel->boot();
     // Restore and merge settings.
     // DrupalKernel::boot() initializes new Settings, and the containerBuild()
     // method sets additional settings.
     new Settings($settings + Settings::getAll());
     // Set the request scope.
     $this->container = $this->kernel->getContainer();
     $this->container->get('request_stack')->push($request);
     // Re-inject extension file listings into state, unless the key/value
     // service was overridden (in which case its storage does not exist yet).
     if ($this->container->get('keyvalue') instanceof KeyValueMemoryFactory) {
         $this->container->get('state')->set('system.module.files', $this->moduleFiles);
         $this->container->get('state')->set('system.theme.files', $this->themeFiles);
     }
     // Create a minimal core.extension configuration object so that the list of
     // enabled modules can be maintained allowing
     // \Drupal\Core\Config\ConfigInstaller::installDefaultConfig() to work.
     // Write directly to active storage to avoid early instantiation of
     // the event dispatcher which can prevent modules from registering events.
     \Drupal::service('config.storage')->write('core.extension', array('module' => array(), 'theme' => array()));
     // Collect and set a fixed module list.
     $class = get_class($this);
     $modules = array();
     while ($class) {
         if (property_exists($class, 'modules')) {
             // Only add the modules, if the $modules property was not inherited.
             $rp = new \ReflectionProperty($class, 'modules');
             if ($rp->class == $class) {
                 $modules[$class] = $class::$modules;
             }
         }
         $class = get_parent_class($class);
     }
     // Modules have been collected in reverse class hierarchy order; modules
     // defined by base classes should be sorted first. Then, merge the results
     // together.
     $modules = array_reverse($modules);
     $modules = call_user_func_array('array_merge_recursive', $modules);
     if ($modules) {
         $this->enableModules($modules);
     }
     // In order to use theme functions default theme config needs to exist.
     \Drupal::config('system.theme')->set('default', 'stark');
     // Tests based on this class are entitled to use Drupal's File and
     // StreamWrapper APIs.
     // @todo Move StreamWrapper management into DrupalKernel.
     // @see https://drupal.org/node/2028109
     file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
     $this->settingsSet('file_public_path', $this->public_files_directory);
     $this->streamWrappers = array();
     $this->registerStreamWrapper('public', 'Drupal\\Core\\StreamWrapper\\PublicStream');
     // The temporary stream wrapper is able to operate both with and without
     // configuration.
     $this->registerStreamWrapper('temporary', 'Drupal\\Core\\StreamWrapper\\TemporaryStream');
 }