/**
  * Sets up the relevant migrations for import from a database connection.
  *
  * @param array|\Drupal\Core\Database\Database $database
  *   Database array representing the source Drupal database.
  * @param string $source_base_path
  *   Address of the source Drupal site (e.g., http://example.com/).
  *
  * @return int[]
  *   An array of Migration entity IDs.
  *
  * @throws \Exception
  */
 protected function getMigrationTemplates(array $database, $source_base_path)
 {
     // Set up the connection.
     $connection = $this->getConnection($database);
     if (!($drupal_version = $this->getLegacyDrupalVersion($connection))) {
         throw new \Exception('Source database does not contain a recognizable Drupal version.');
     }
     $database_state['key'] = 'upgrade';
     $database_state['database'] = $database;
     $database_state_key = 'migrate_upgrade_' . $drupal_version;
     \Drupal::state()->set($database_state_key, $database_state);
     $version_tag = 'Drupal ' . $drupal_version;
     $template_storage = \Drupal::service('migrate.template_storage');
     $migration_templates = $template_storage->findTemplatesByTag($version_tag);
     foreach ($migration_templates as $id => $template) {
         $migration_templates[$id]['source']['database_state_key'] = $database_state_key;
         // Configure file migrations so they can find the files.
         if ($template['destination']['plugin'] == 'entity:file') {
             if ($source_base_path) {
                 // Make sure we have a single trailing slash.
                 $source_base_path = rtrim($source_base_path, '/') . '/';
                 $migration_templates[$id]['destination']['source_base_path'] = $source_base_path;
             }
         }
     }
     return $migration_templates;
 }
 /**
  * Tests the missing content event is fired.
  *
  * @see \Drupal\Core\Config\ConfigImporter::processMissingContent()
  * @see \Drupal\config_import_test\EventSubscriber
  */
 function testMissingContent()
 {
     \Drupal::state()->set('config_import_test.config_import_missing_content', TRUE);
     // Update a configuration entity in the sync directory to have a dependency
     // on two content entities that do not exist.
     $storage = $this->container->get('config.storage');
     $sync = $this->container->get('config.storage.sync');
     $entity_one = entity_create('entity_test', array('name' => 'one'));
     $entity_two = entity_create('entity_test', array('name' => 'two'));
     $entity_three = entity_create('entity_test', array('name' => 'three'));
     $dynamic_name = 'config_test.dynamic.dotted.default';
     $original_dynamic_data = $storage->read($dynamic_name);
     // Entity one will be resolved by
     // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentOne().
     $original_dynamic_data['dependencies']['content'][] = $entity_one->getConfigDependencyName();
     // Entity two will be resolved by
     // \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentTwo().
     $original_dynamic_data['dependencies']['content'][] = $entity_two->getConfigDependencyName();
     // Entity three will be resolved by
     // \Drupal\Core\Config\Importer\FinalMissingContentSubscriber.
     $original_dynamic_data['dependencies']['content'][] = $entity_three->getConfigDependencyName();
     $sync->write($dynamic_name, $original_dynamic_data);
     // Import.
     $this->configImporter->reset()->import();
     $this->assertEqual([], $this->configImporter->getErrors(), 'There were no errors during the import.');
     $this->assertEqual($entity_one->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_one'), 'The missing content event is fired during configuration import.');
     $this->assertEqual($entity_two->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_two'), 'The missing content event is fired during configuration import.');
     $original_dynamic_data = $storage->read($dynamic_name);
     $this->assertEqual([$entity_one->getConfigDependencyName(), $entity_two->getConfigDependencyName(), $entity_three->getConfigDependencyName()], $original_dynamic_data['dependencies']['content'], 'The imported configuration entity has the missing content entity dependency.');
 }
 function setUp()
 {
     parent::setUp();
     $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
     // Create and login user.
     $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval'));
     $this->drupalLogin($admin_user);
     // Add language.
     $edit = array('predefined_langcode' => 'fr');
     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
     // Set "Article" content type to use multilingual support.
     $edit = array('language_configuration[language_show]' => TRUE);
     $this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
     // Enable content language negotiation UI.
     \Drupal::state()->set('language_test.content_language_type', TRUE);
     // Set interface language detection to user and content language detection
     // to URL. Disable inheritance from interface language to ensure content
     // language will fall back to the default language if no URL language can be
     // detected.
     $edit = array('language_interface[enabled][language-user]' => TRUE, 'language_content[enabled][language-url]' => TRUE, 'language_content[enabled][language-interface]' => FALSE);
     $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
     // Change user language preference, this way interface language is always
     // French no matter what path prefix the URLs have.
     $edit = array('preferred_langcode' => 'fr');
     $this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save'));
     // Create comment field on article.
     $this->container->get('comment.manager')->addDefaultField('node', 'article');
     // Make comment body translatable.
     $field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
     $field_storage->translatable = TRUE;
     $field_storage->save();
     $this->assertTrue($field_storage->isTranslatable(), 'Comment body is translatable.');
 }
Example #4
0
 /**
  * Tests hook_post_update_NAME().
  */
 public function testPostUpdate()
 {
     $this->runUpdates();
     $this->assertRaw('<h3>Update first</h3>');
     $this->assertRaw('First update');
     $this->assertRaw('<h3>Update second</h3>');
     $this->assertRaw('Second update');
     $this->assertRaw('<h3>Update test1</h3>');
     $this->assertRaw('Test1 update');
     $this->assertRaw('<h3>Update test0</h3>');
     $this->assertRaw('Test0 update');
     $this->assertRaw('<h3>Update test_batch</h3>');
     $this->assertRaw('Test post update batches');
     // Test state value set by each post update.
     $updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch-1', 'update_test_postupdate_post_update_test_batch-2', 'update_test_postupdate_post_update_test_batch-3'];
     $this->assertIdentical($updates, \Drupal::state()->get('post_update_test_execution', []));
     // Test post_update key value stores contains a list of the update functions
     // that have run.
     $existing_updates = array_count_values(\Drupal::keyValue('post_update')->get('existing_updates'));
     $expected_updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch'];
     foreach ($expected_updates as $expected_update) {
         $this->assertEqual($existing_updates[$expected_update], 1, new FormattableMarkup("@expected_update exists in 'existing_updates' key and only appears once.", ['@expected_update' => $expected_update]));
     }
     $this->drupalGet('update.php/selection');
     $this->assertText('No pending updates.');
 }
 /**
  * {@inheritdoc}
  */
 public static function getSubscribedEvents()
 {
     // Register this listener for every event that is used by a reaction rule.
     $events = [];
     $callback = ['onRulesEvent', 100];
     // If there is no state service there is nothing we can do here. This static
     // method could be called early when the container is built, so the state
     // service might no always be available.
     if (!\Drupal::hasService('state')) {
         return [];
     }
     // Since we cannot access the reaction rule config storage here we have to
     // use the state system to provide registered Rules events. The Reaction
     // Rule storage is responsible for keeping the registered events up to date
     // in the state system.
     // @see \Drupal\rules\Entity\ReactionRuleStorage
     $state = \Drupal::state();
     $registered_event_names = $state->get('rules.registered_events');
     if (!empty($registered_event_names)) {
         foreach ($registered_event_names as $event_name) {
             $events[$event_name][] = $callback;
         }
     }
     return $events;
 }
 /**
  * Overrides Mollom::__construct().
  *
  * This class accounts for multiple scenarios:
  * - Straight low-level requests against the testing API from a custom script,
  *   caring for API keys on its own.
  * - Whenever the testing mode is enabled (either through the module's
  *   settings page or by changing the testing_mode system variable),
  *   the client requires valid testing API keys to perform any calls. Testing
  *   API keys are different to production API keys, need to be created first,
  *   and may vanish at any time (whenever the testing API server is
  *   redeployed). Since they are different, the class stores them in different
  *   system variables. Since they can vanish at any time, the class verifies
  *   the keys upon every instantiation, and automatically creates new testing
  *   API keys if necessary.
  * - Some automated unit tests attempt to verify that authentication errors
  *   are handled correctly by the class' error handling. The automatic
  *   creation and recovery of testing API keys would break those assertions,
  *   so said tests can disable the behavior by preemptively setting
  *   $createKeys or the 'mollom.testing_create_keys' state variable to FALSE,
  *   and manually create testing API keys (once).
  *
  * Constructor.
  * @param ConfigFactory $config_factory
  * @param ClientInterface $http_client
  *
  * @see Mollom::__construct().
  */
 public function __construct(ConfigFactory $config_factory, ClientInterface $http_client)
 {
     $this->config = $config_factory->get('mollom.settings');
     // Some tests are verifying the production behavior of e.g. setting up API
     // keys, in which testing mode is NOT enabled and the test creates fake
     // "production" API keys on the local fake server on its own. This special
     // override must only be possible when executing tests.
     // @todo Add global test_info as condition?
     $testing_mode = $this->config->get('test_mode.enabled');
     $module_exists = \Drupal::moduleHandler()->moduleExists('mollom_test_server');
     if ($module_exists && !$testing_mode) {
         // Disable authentication error auto-recovery.
         $this->createKeys = FALSE;
     } else {
         // Do not destroy production variables when testing mode is enabled.
         $this->configuration_map['publicKey'] = 'test_mode.keys.public';
         $this->configuration_map['privateKey'] = 'test_mode.keys.private';
         $this->configuration_map['server'] = 'test_mode.api_endpoint';
     }
     // Load and set publicKey and privateKey configuration values.
     parent::__construct($config_factory, $http_client);
     // Unless pre-set, determine whether API keys should be auto-created.
     if (!isset($this->createKeys)) {
         $this->createKeys = \Drupal::state()->get('mollom.testing_create_keys') ?: TRUE;
     }
     // Testing can require additional time.
     $this->requestTimeout = $this->config->get('connection_timeout_seconds', 3) + 10;
 }
Example #7
0
 /**
  * Take the site online if it was taken offline for this operation.
  */
 protected function takeSiteOnline()
 {
     // Take the site online again.
     if ($this->maintenance_mode) {
         \Drupal::state()->set('system.maintenance_mode', FALSE);
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->moduleHandler = $this->container->get('module_handler');
     $this->projectStorage = $this->container->get('locale.project');
     \Drupal::state()->set('locale.remove_core_project', TRUE);
 }
 protected function setUp()
 {
     parent::setUp();
     // Let there be T-rex.
     \Drupal::state()->set('editor_test_give_me_a_trex_thanks', TRUE);
     \Drupal::service('plugin.manager.editor')->clearCachedDefinitions();
     // Add text formats.
     $filtered_html_format = entity_create('filter_format', array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
     $filtered_html_format->save();
     $full_html_format = entity_create('filter_format', array('format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => array()));
     $full_html_format->save();
     // Create article node type.
     $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
     // Create page node type, but remove the body.
     $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Page'));
     $body = FieldConfig::loadByName('node', 'page', 'body');
     $body->delete();
     // Create a formatted text field, which uses an <input type="text">.
     FieldStorageConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text'))->save();
     FieldConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'label' => 'Textfield', 'bundle' => 'page'))->save();
     entity_get_form_display('node', 'page', 'default')->setComponent('field_text')->save();
     // Create 3 users, each with access to different text formats.
     $this->untrustedUser = $this->drupalCreateUser(array('create article content', 'edit any article content'));
     $this->normalUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'use text format filtered_html'));
     $this->privilegedUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'create page content', 'edit any page content', 'use text format filtered_html', 'use text format full_html'));
 }
 /**
  * Tests running update.php with some form of broken routing.
  */
 public function testWithBrokenRouting()
 {
     // Make sure we can get to the front page.
     $this->drupalGet('<front>');
     $this->assertResponse(200);
     // Simulate a broken router, and make sure the front page is
     // inaccessible.
     \Drupal::state()->set('update_script_test_broken_inbound', TRUE);
     \Drupal::service('cache_tags.invalidator')->invalidateTags(['route_match', 'rendered']);
     $this->drupalGet('<front>');
     $this->assertResponse(500);
     // The exceptions are expected. Do not interpret them as a test failure.
     // Not using File API; a potential error must trigger a PHP warning.
     unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
     foreach ($this->assertions as $key => $assertion) {
         if (strpos($assertion['message'], 'core/modules/system/tests/modules/update_script_test/src/PathProcessor/BrokenInboundPathProcessor.php') !== FALSE) {
             unset($this->assertions[$key]);
             $this->deleteAssert($assertion['message_id']);
         }
     }
     $this->runUpdates();
     // Remove the simulation of the broken router, and make sure we can get to
     // the front page again.
     \Drupal::state()->set('update_script_test_broken_inbound', FALSE);
     $this->drupalGet('<front>');
     $this->assertResponse(200);
 }
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
     if ($is_admin) {
         return [];
     }
     global $base_url;
     $output['#theme'] = "searchblox_frontend_view";
     $output['#var1'] = "vars_set_from_module_file";
     $output['#type'] = "markup";
     $output['#attributes'] = ['class' => ['searchblox-div']];
     // Prepare Vars For Setting them in Drupal.Settings
     $search_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/SearchServlet' : '';
     $auto_suggest_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/AutoSuggest' : '';
     $report_servlet_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/ReportServlet' : '';
     $full_plugin_url = searchblox_full_plugin_url();
     $collection_ids = array();
     $collection_ids = \Drupal::state()->get('searchblox_collection_ids') ? \Drupal::state()->get('searchblox_collection_ids') : '';
     $output['#attached']['drupalSettings']["searchblox"]["base_url"] = $base_url;
     $output['#attached']['drupalSettings']["searchblox"]["module_url"] = $base_url . "/modules/searchblox";
     $output['#attached']['drupalSettings']["searchblox"]["search_url"] = $search_url;
     $output['#attached']['drupalSettings']["searchblox"]["auto_suggest_url"] = $auto_suggest_url;
     $output['#attached']['drupalSettings']["searchblox"]["report_servlet_url"] = $report_servlet_url;
     $output['#attached']['drupalSettings']["searchblox"]["full_plugin_url"] = $full_plugin_url;
     $output['#attached']['drupalSettings']["searchblox"]["collection_ids"] = $collection_ids;
     // Attach Library
     $output['#attached']['library'][] = 'searchblox/searchblox-frontpage';
     $this->rendered_content = $output;
     return $output;
 }
 /**
  * Test validation.
  */
 function testValidation()
 {
     $state = \Drupal::state();
     $path = 'currency_test-form-element-currency-sign';
     // Test an empty sign.
     $values = array('container[sign][sign]' => '');
     $this->drupalPostForm($path, $values, t('Submit'));
     $sign = $state->get('currency_test_currency_sign_element');
     $this->assertEqual('', $sign);
     // Test a suggested sign.
     $values = array('container[sign][sign]' => '€');
     $this->drupalPostForm($path . '/EUR', $values, t('Submit'));
     $sign = $state->get('currency_test_currency_sign_element');
     $this->assertEqual('€', $sign);
     // Test a custom sign.
     $values = array('container[sign][sign]' => CurrencySign::CUSTOM_VALUE, 'container[sign][sign_custom]' => 'foobar');
     $this->drupalPostForm($path, $values, t('Submit'));
     $sign = $state->get('currency_test_currency_sign_element');
     $this->assertEqual('foobar', $sign);
     $this->drupalGet($path . '/EUR/foobar');
     $this->assertRaw('<option value="' . CurrencySign::CUSTOM_VALUE . '" selected="selected">');
     // Check if the sign element is set to a custom value.
     $this->assertFieldByXPath("//select[@name='container[sign][sign]']/option[@value='" . CurrencySign::CUSTOM_VALUE . "' and @selected='selected']");
     // Check if the custom sign input element has the custom sign as its value.
     $this->assertFieldByXPath("//input[@name='container[sign][sign_custom]' and @value='foobar']");
     // Test a non-existing currency.
     $values = array('container[sign][sign]' => '');
     $this->drupalPostForm($path . '/ZZZ', $values, t('Submit'));
     $sign = $state->get('currency_test_currency_sign_element');
     $this->assertEqual('', $sign);
 }
Example #13
0
 /**
  * Checks the From: and Reply-to: headers.
  */
 public function testFromAndReplyToHeader()
 {
     $language = \Drupal::languageManager()->getCurrentLanguage();
     // Use the state system collector mail backend.
     \Drupal::config('system.mail')->set('interface.default', 'test_mail_collector')->save();
     // Reset the state variable that holds sent messages.
     \Drupal::state()->set('system.test_mail_collector', array());
     // Send an email with a reply-to address specified.
     $from_email = 'Drupal <*****@*****.**>';
     $reply_email = '*****@*****.**';
     drupal_mail('simpletest', 'from_test', '*****@*****.**', $language, array(), $reply_email);
     // Test that the reply-to email is just the email and not the site name
     // and default sender email.
     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
     $sent_message = end($captured_emails);
     $this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
     $this->assertEqual($reply_email, $sent_message['headers']['Reply-to'], 'Message reply-to headers are set.');
     $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
     // Send an email and check that the From-header contains the site name.
     drupal_mail('simpletest', 'from_test', '*****@*****.**', $language);
     $captured_emails = \Drupal::state()->get('system.test_mail_collector');
     $sent_message = end($captured_emails);
     $this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
     $this->assertFalse(isset($sent_message['headers']['Reply-to']), 'Message reply-to is not set if not specified.');
     $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
 }
 /**
  * Tests the rediscovering.
  */
 public function testRediscover()
 {
     \Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_1' => new Route('/example-path')]);
     \Drupal::service('router.builder')->rebuild();
     // Set up a custom menu link pointing to a specific path.
     MenuLinkContent::create(['title' => '<script>alert("Welcome to the discovered jungle!")</script>', 'link' => [['uri' => 'internal:/example-path']], 'menu_name' => 'tools'])->save();
     $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
     $this->assertEqual(1, count($menu_tree));
     /** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
     $tree_element = reset($menu_tree);
     $this->assertEqual('route_name_1', $tree_element->link->getRouteName());
     // Change the underlying route and trigger the rediscovering.
     \Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_2' => new Route('/example-path')]);
     \Drupal::service('router.builder')->rebuild();
     // Ensure that the new route name / parameters are captured by the tree.
     $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
     $this->assertEqual(1, count($menu_tree));
     /** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
     $tree_element = reset($menu_tree);
     $this->assertEqual('route_name_2', $tree_element->link->getRouteName());
     $title = $tree_element->link->getTitle();
     $this->assertFalse($title instanceof TranslationWrapper);
     $this->assertIdentical('<script>alert("Welcome to the discovered jungle!")</script>', $title);
     $this->assertFalse(SafeMarkup::isSafe($title));
 }
 function setUp()
 {
     parent::setUp();
     node_access_rebuild();
     node_access_test_add_field(entity_load('node_type', 'forum'));
     \Drupal::state()->set('node_access_test.private', TRUE);
 }
 /**
  * Test validation.
  */
 function testValidation()
 {
     $state = \Drupal::state();
     $path = 'currency_test-form-element-currency-amount/50.00/100';
     // Test valid values.
     $values = array('container[amount][amount]' => '50,95', 'container[amount][currency_code]' => 'EUR');
     $this->drupalPostForm($path, $values, t('Submit'));
     $amount = $state->get('currency_test_currency_amount_element');
     $this->assertEqual(50.95, $amount['amount']);
     $this->assertEqual('EUR', $amount['currency_code']);
     // Test valid values with a predefined currency.
     $this->drupalGet($path . '/NLG');
     $this->assertNoFieldByXPath("//input[@name='container[amount][currency_code]']");
     $values = array('container[amount][amount]' => '50,95');
     $this->drupalPostForm($path . '/NLG', $values, t('Submit'));
     $amount = $state->get('currency_test_currency_amount_element');
     $this->assertEqual(50.95, $amount['amount']);
     $this->assertEqual('NLG', $amount['currency_code']);
     // Test invalid values.
     $invalid_amounts = array($this->randomMachineName(2), '49,.95', '49.95', '999');
     foreach ($invalid_amounts as $amount) {
         $values = array('container[amount][amount]' => $amount);
         $this->drupalPostForm($path, $values, t('Submit'));
         $this->assertFieldByXPath("//input[@name='container[amount][amount]' and contains(@class, 'error')]");
         $this->assertNoFieldByXPath("//input[not(@name='container[amount][amount]') and contains(@class, 'error')]");
     }
 }
 /**
  * Tests that page title is being converted into a block.
  */
 public function testUpdateHookN()
 {
     $this->runUpdates();
     /** @var \Drupal\block\BlockInterface $block_storage */
     $block_storage = \Drupal::entityManager()->getStorage('block');
     $this->assertRaw('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page templates.');
     // Disable maintenance mode.
     // @todo Can be removed once maintenance mode is automatically turned off
     // after updates in https://www.drupal.org/node/2435135.
     \Drupal::state()->set('system.maintenance_mode', FALSE);
     // We finished updating so we can log in the user now.
     $this->drupalLogin($this->rootUser);
     $page = Node::create(['type' => 'page', 'title' => 'Page node']);
     $page->save();
     // Page title is visible on the home page.
     $this->drupalGet('/node');
     $this->assertRaw('page-title');
     // Page title is visible on a node page.
     $this->drupalGet('node/' . $page->id());
     $this->assertRaw('page-title');
     $this->drupalGet('admin/structure/block/list/bartik');
     /** @var \Drupal\Core\Config\StorageInterface $config_storage */
     $config_storage = \Drupal::service('config.storage');
     $this->assertTrue($config_storage->exists('block.block.test_theme_page_title'), 'Page title block has been created for the custom theme.');
 }
Example #18
0
 /**
  * Asserts whether expected exceptions are thrown for invalid hook implementations.
  *
  * @param string $module
  *   The module whose invalid logic in its hooks to enable.
  * @param string $hook
  *   The page render hook to assert expected exceptions for.
  */
 function assertPageRenderHookExceptions($module, $hook)
 {
     $html_renderer = \Drupal::getContainer()->get('main_content_renderer.html');
     // Assert a valid hook implementation doesn't trigger an exception.
     $page = [];
     $html_renderer->invokePageAttachmentHooks($page);
     // Assert that hooks can set cache tags.
     $this->assertEqual($page['#cache']['tags'], ['example']);
     $this->assertEqual($page['#cache']['contexts'], ['user.permissions']);
     // Assert an invalid hook implementation doesn't trigger an exception.
     \Drupal::state()->set($module . '.' . $hook . '.descendant_attached', TRUE);
     $assertion = $hook . '() implementation that sets #attached on a descendant triggers an exception';
     $page = [];
     try {
         $html_renderer->invokePageAttachmentHooks($page);
         $this->error($assertion);
     } catch (\LogicException $e) {
         $this->pass($assertion);
         $this->assertEqual($e->getMessage(), 'Only #attached, #post_render_cache and #cache may be set in ' . $hook . '().');
     }
     \Drupal::state()->set('bc_test.' . $hook . '.descendant_attached', FALSE);
     // Assert an invalid hook implementation doesn't trigger an exception.
     \Drupal::state()->set('bc_test.' . $hook . '.render_array', TRUE);
     $assertion = $hook . '() implementation that sets a child render array triggers an exception';
     $page = [];
     try {
         $html_renderer->invokePageAttachmentHooks($page);
         $this->error($assertion);
     } catch (\LogicException $e) {
         $this->pass($assertion);
         $this->assertEqual($e->getMessage(), 'Only #attached, #post_render_cache and #cache may be set in ' . $hook . '().');
     }
     \Drupal::state()->set($module . '.' . $hook . '.render_array', FALSE);
 }
 /**
  * Tests entity info cache after enabling a module with a dependency on an entity providing module.
  *
  * @see entity_cache_test_modules_enabled()
  */
 function testEntityInfoCacheModulesEnabled()
 {
     \Drupal::moduleHandler()->install(array('entity_cache_test'));
     $entity_type = \Drupal::state()->get('entity_cache_test');
     $this->assertEqual($entity_type->getLabel(), 'Entity Cache Test', 'Entity info label is correct.');
     $this->assertEqual($entity_type->getStorageClass(), 'Drupal\\Core\\Entity\\EntityDatabaseStorage', 'Entity controller class info is correct.');
 }
Example #20
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $modules = $input->getArgument('module');
     $module_handler = $this->getDrupalService('module_handler');
     $lock = $this->getDrupalService('lock');
     // Try to acquire cron lock.
     if (!$lock->acquire('cron', 900.0)) {
         $io->warning($this->trans('commands.cron.execute.messages.lock'));
         return;
     }
     if (in_array('all', $modules)) {
         $modules = $module_handler->getImplementations('cron');
     }
     foreach ($modules as $module) {
         if ($module_handler->implementsHook($module, 'cron')) {
             $io->info(sprintf($this->trans('commands.cron.execute.messages.executing-cron'), $module));
             try {
                 $module_handler->invoke($module, 'cron');
             } catch (\Exception $e) {
                 watchdog_exception('cron', $e);
                 $io->error($e->getMessage());
             }
         } else {
             $io->warning(sprintf($this->trans('commands.cron.execute.messages.module-invalid'), $module));
         }
     }
     // Set last time cron was executed
     \Drupal::state()->set('system.cron_last', REQUEST_TIME);
     // Release cron lock.
     $lock->release('cron');
     $this->get('chain_queue')->addCommand('cache:rebuild', ['cache' => 'all']);
     $io->success($this->trans('commands.cron.execute.messages.success'));
 }
Example #21
0
 /**
  * Tests the form cache with a logged-in user.
  */
 function testCacheToken()
 {
     \Drupal::currentUser()->setAccount(new UserSession(array('uid' => 1)));
     \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);
     $cached_form_state = new FormState();
     $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
     $this->assertEqual($this->form['#property'], $cached_form['#property']);
     $this->assertTrue(!empty($cached_form['#cache_token']), 'Form has a cache token');
     $this->assertEqual($this->formState->get('example'), $cached_form_state->get('example'));
     // Test that the form cache isn't loaded when the session/token has changed.
     // Change the private key. (We cannot change the session ID because this
     // will break the parent site test runner batch.)
     \Drupal::state()->set('system.private_key', 'invalid');
     $cached_form_state = new FormState();
     $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
     $this->assertFalse($cached_form, 'No form returned from cache');
     $cached_form_state_example = $cached_form_state->get('example');
     $this->assertTrue(empty($cached_form_state_example));
     // Test that loading the cache with a different form_id fails.
     $wrong_form_build_id = $this->randomMachineName(9);
     $cached_form_state = new FormState();
     $this->assertFalse(\Drupal::formBuilder()->getCache($wrong_form_build_id, $cached_form_state), 'No form returned from cache');
     $cached_form_state_example = $cached_form_state->get('example');
     $this->assertTrue(empty($cached_form_state_example), 'Cached form state was not loaded');
 }
 /**
  * Test update changes configuration translations if enabled after language.
  */
 public function testConfigTranslationImport()
 {
     $admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions'));
     $this->drupalLogin($admin_user);
     // Add a language. The Afrikaans translation file of locale_test_translate
     // (test.af.po) has been prepared with a configuration translation.
     ConfigurableLanguage::createFromLangcode('af')->save();
     // Enable locale module.
     $this->container->get('module_installer')->install(array('locale'));
     $this->resetAll();
     // Enable import of translations. By default this is disabled for automated
     // tests.
     $this->config('locale.settings')->set('translation.import_enabled', TRUE)->save();
     // Add translation permissions now that the locale module has been enabled.
     $edit = array('authenticated[translate interface]' => 'translate interface');
     $this->drupalPostForm('admin/people/permissions', $edit, t('Save permissions'));
     // Check and update the translation status. This will import the Afrikaans
     // translations of locale_test_translate module.
     $this->drupalGet('admin/reports/translations/check');
     // Override the Drupal core translation status to be up to date.
     // Drupal core should not be a subject in this test.
     $status = locale_translation_get_status();
     $status['drupal']['af']->type = 'current';
     \Drupal::state()->set('locale.translation_status', $status);
     $this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
     // Check if configuration translations have been imported.
     $override = \Drupal::languageManager()->getLanguageConfigOverride('af', 'system.maintenance');
     $this->assertEqual($override->get('message'), 'Ons is tans besig met onderhoud op @site. Wees asseblief geduldig, ons sal binnekort weer terug wees.');
 }
 /**
  * Tests that local actions/tasks are being converted into blocks.
  */
 public function testUpdateHookN()
 {
     $this->runUpdates();
     /** @var \Drupal\block\BlockInterface $block_storage */
     $block_storage = \Drupal::entityManager()->getStorage('block');
     /* @var \Drupal\block\BlockInterface[] $help_blocks */
     $help_blocks = $block_storage->loadByProperties(['theme' => 'bartik', 'region' => 'help']);
     $this->assertRaw('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
     // Disable maintenance mode.
     // @todo Can be removed once maintenance mode is automatically turned off
     // after updates in https://www.drupal.org/node/2435135.
     \Drupal::state()->set('system.maintenance_mode', FALSE);
     // We finished updating so we can log in the user now.
     $this->drupalLogin($this->rootUser);
     $page = Node::create(['type' => 'page', 'title' => 'Page node']);
     $page->save();
     // Ensures that blocks inside help region has been moved to content region.
     foreach ($help_blocks as $block) {
         $new_block = $block_storage->load($block->id());
         $this->assertEqual($new_block->getRegion(), 'content');
     }
     // Local tasks are visible on the node page.
     $this->drupalGet('node/' . $page->id());
     $this->assertText(t('Edit'));
     // Local actions are visible on the content listing page.
     $this->drupalGet('admin/content');
     $action_link = $this->cssSelect('.action-links');
     $this->assertTrue($action_link);
     $this->drupalGet('admin/structure/block/list/seven');
     /** @var \Drupal\Core\Config\StorageInterface $config_storage */
     $config_storage = \Drupal::service('config.storage');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_tasks'), 'Local task block has been created for the custom theme.');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_actions'), 'Local action block has been created for the custom theme.');
 }
 /**
  * Implements MailSystemInterface::mail().
  */
 public function mail(array $message)
 {
     $captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: array();
     $captured_emails[] = $message;
     \Drupal::state()->set('system.test_mail_collector', $captured_emails);
     return TRUE;
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function isInstalled()
 {
     // Check if the module exists in the file system, regardless of whether it
     // is enabled or not.
     $modules = \Drupal::state()->get('system.module.files', array());
     return isset($modules[$this->name]);
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, FormStateInterface $form_state)
 {
     try {
         $entity = $this->entity;
         // Save as a new revision if requested to do so.
         if (!$form_state->isValueEmpty('revision')) {
             $entity->setNewRevision();
         }
         $is_new = $entity->isNew();
         $entity->save();
         if ($is_new) {
             $message = t('%entity_type @id has been created.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()));
         } else {
             $message = t('%entity_type @id has been updated.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId()));
         }
         drupal_set_message($message);
         if ($entity->id()) {
             $entity_type = $entity->getEntityTypeId();
             $form_state->setRedirect("entity.{$entity_type}.edit_form", array($entity_type => $entity->id()));
         } else {
             // Error on save.
             drupal_set_message(t('The entity could not be saved.'), 'error');
             $form_state->setRebuild();
         }
     } catch (\Exception $e) {
         \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage());
     }
 }
 protected function setUp()
 {
     parent::setUp();
     node_access_test_add_field(NodeType::load('article'));
     node_access_rebuild();
     \Drupal::state()->set('node_access_test.private', TRUE);
 }
Example #28
0
 /**
  * Tests the configurable text editor manager.
  */
 public function testManager()
 {
     $this->editorManager = $this->container->get('plugin.manager.editor');
     // Case 1: no text editor available:
     // - listOptions() should return an empty list of options
     // - getAttachments() should return an empty #attachments array (and not
     //   a JS settings structure that is empty)
     $this->assertIdentical(array(), $this->editorManager->listOptions(), 'When no text editor is enabled, the manager works correctly.');
     $this->assertIdentical(array(), $this->editorManager->getAttachments(array()), 'No attachments when no text editor is enabled and retrieving attachments for zero text formats.');
     $this->assertIdentical(array(), $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'No attachments when no text editor is enabled and retrieving attachments for multiple text formats.');
     // Enable the Text Editor Test module, which has the Unicorn Editor and
     // clear the editor manager's cache so it is picked up.
     $this->enableModules(array('editor_test'));
     $this->editorManager = $this->container->get('plugin.manager.editor');
     $this->editorManager->clearCachedDefinitions();
     // Case 2: a text editor available.
     $this->assertIdentical('Unicorn Editor', (string) $this->editorManager->listOptions()['unicorn'], 'When some text editor is enabled, the manager works correctly.');
     // Case 3: a text editor available & associated (but associated only with
     // the 'Full HTML' text format).
     $unicorn_plugin = $this->editorManager->createInstance('unicorn');
     $editor = entity_create('editor', array('format' => 'full_html', 'editor' => 'unicorn'));
     $editor->save();
     $this->assertIdentical(array(), $this->editorManager->getAttachments(array()), 'No attachments when one text editor is enabled and retrieving attachments for zero text formats.');
     $expected = array('library' => array(0 => 'editor_test/unicorn'), 'drupalSettings' => ['editor' => ['formats' => ['full_html' => ['format' => 'full_html', 'editor' => 'unicorn', 'editorSettings' => $unicorn_plugin->getJSSettings($editor), 'editorSupportsContentFiltering' => TRUE, 'isXssSafe' => FALSE]]]]);
     $this->assertIdentical($expected, $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'Correct attachments when one text editor is enabled and retrieving attachments for multiple text formats.');
     // Case 4: a text editor available associated, but now with its JS settings
     // being altered via hook_editor_js_settings_alter().
     \Drupal::state()->set('editor_test_js_settings_alter_enabled', TRUE);
     $expected['drupalSettings']['editor']['formats']['full_html']['editorSettings']['ponyModeEnabled'] = FALSE;
     $this->assertIdentical($expected, $this->editorManager->getAttachments(array('filtered_html', 'full_html')), 'hook_editor_js_settings_alter() works correctly.');
 }
 /**
  * Assert translations JS is added before drupal.js, because it depends on it.
  */
 public function testLocaleTranslationJsDependencies()
 {
     // User to add and remove language.
     $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
     // Add custom language.
     $this->drupalLogin($admin_user);
     // Code for the language.
     $langcode = 'es';
     // The English name for the language.
     $name = $this->randomMachineName(16);
     // The domain prefix.
     $prefix = $langcode;
     $edit = array('predefined_langcode' => 'custom', 'langcode' => $langcode, 'label' => $name, 'direction' => LanguageInterface::DIRECTION_LTR);
     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
     // Set path prefix.
     $edit = array("prefix[{$langcode}]" => $prefix);
     $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
     // This forces locale.admin.js string sources to be imported, which contains
     // the next translation.
     $this->drupalGet($prefix . '/admin/config/regional/translate');
     // Translate a string in locale.admin.js to our new language.
     $strings = \Drupal::service('locale.storage')->getStrings(array('source' => 'Show description', 'type' => 'javascript', 'name' => 'core/modules/locale/locale.admin.js'));
     $string = $strings[0];
     $this->drupalPostForm(NULL, ['string' => 'Show description'], t('Filter'));
     $edit = ['strings[' . $string->lid . '][translations][0]' => $this->randomString(16)];
     $this->drupalPostForm(NULL, $edit, t('Save translations'));
     // Calculate the filename of the JS including the translations.
     $js_translation_files = \Drupal::state()->get('locale.translation.javascript');
     $js_filename = $prefix . '_' . $js_translation_files[$prefix] . '.js';
     // Assert translations JS is included before drupal.js.
     $this->assertTrue(strpos($this->content, $js_filename) < strpos($this->content, 'core/misc/drupal.js'), 'Translations are included before Drupal.t.');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $state = \Drupal::state();
     $submit_count = (int) $state->get('search_embedded_form.submit_count');
     $state->set('search_embedded_form.submit_count', $submit_count + 1);
     drupal_set_message($this->t('Test form was submitted'));
 }