public function index($count) { // Esta forma de llevar a cabo conexiones es mas rapida sin usar dependency injection // sin embargo es considerada mala practica // $connection = \Drupal::database(); $select = $this->db->select('node', 'n'); $select->fields('n'); $select->range(0, $count); $result = $select->execute()->fetchAll(); $query = $this->entityQuery->get('node'); $query->condition('status', 1); $query->range(0, $count); $result = $query->execute(); $storage = $this->entityManager->getStorage('node'); $render_controller = $this->entityManager->getViewBuilder('node'); $nodes = $storage->loadMultiple($result); $some_nodes = array(); foreach ($nodes as $nid => $node) { $some_nodes[$nid] = $node->getTitle(); } $dispatcher = $this->eventDisp; $e = new NodeFancyDisplayEvent($some_nodes); $event = $dispatcher->dispatch('rootstack_sandbox.fancy_node_edit', $e); $some_nodes = $event->getFancyNodes(); // Generar links en D8..... http://drupal.stackexchange.com/questions/144992/how-do-you-create-a-link-in-drupal-8 :( $block = \Drupal\block\Entity\Block::load('views_block__sdf_block_1'); $test = $this->entityManager->getViewBuilder('block')->view($block); return ['#theme' => 'fancy_nodes', '#summary' => $render_controller->view(array_values($nodes)[0]), '#some_nodes' => $some_nodes, '#total' => count($nodes)]; }
/** * Tests the rendering of blocks. */ public function testBasicRendering() { \Drupal::state()->set('block_test.content', ''); $entity = $this->controller->create(array('id' => 'test_block1', 'theme' => 'stark', 'plugin' => 'test_html')); $entity->save(); // Test the rendering of a block. $entity = Block::load('test_block1'); $output = entity_view($entity, 'block'); $expected = array(); $expected[] = '<div id="block-test-block1">'; $expected[] = ' '; $expected[] = ' '; $expected[] = ' '; $expected[] = ' </div>'; $expected[] = ''; $expected_output = implode("\n", $expected); $this->assertEqual($this->renderer->renderRoot($output), $expected_output); // Reset the HTML IDs so that the next render is not affected. Html::resetSeenIds(); // Test the rendering of a block with a given title. $entity = $this->controller->create(array('id' => 'test_block2', 'theme' => 'stark', 'plugin' => 'test_html', 'settings' => array('label' => 'Powered by Bananas'))); $entity->save(); $output = entity_view($entity, 'block'); $expected = array(); $expected[] = '<div id="block-test-block2">'; $expected[] = ' '; $expected[] = ' <h2>Powered by Bananas</h2>'; $expected[] = ' '; $expected[] = ' '; $expected[] = ' </div>'; $expected[] = ''; $expected_output = implode("\n", $expected); $this->assertEqual($this->renderer->renderRoot($output), $expected_output); }
/** * Tests the functionality of the Printable block. */ public function testPrintableBlock() { $this->drupalLogin($this->adminUser); $edit = ['id' => strtolower($this->randomMachineName()), 'settings[label]' => $this->randomMachineName(8), 'region' => 'sidebar_first', 'visibility[node_type][bundles][article]' => 'article']; $theme = \Drupal::service('theme_handler')->getDefault(); $this->drupalPostForm("admin/structure/block/add/printable_links_block%3Anode/{$theme}", $edit, t('Save block')); $block = Block::load($edit['id']); $visibility = $block->getVisibility(); $this->assertTrue(isset($visibility['node_type']['bundles']['article']), 'Visibility settings were saved to configuration'); // Test deleting the block from the edit form. $this->drupalGet('admin/structure/block/manage/' . $edit['id']); $this->clickLink(t('Delete')); $this->assertRaw(t('Are you sure you want to delete the block %name?', array('%name' => $edit['settings[label]']))); $this->drupalPostForm(NULL, array(), t('Delete')); $this->assertRaw(t('The block %name has been deleted.', array('%name' => $edit['settings[label]']))); }
/** * Tests that block context mapping is updated properly. */ public function testUpdateHookN() { $this->runUpdates(); $this->assertRaw('Encountered an unknown context mapping key coming probably from a contributed or custom module: One or more mappings could not be updated. Please manually review your visibility settings for the following blocks, which are disabled now:<ul><li>User login (Visibility: Baloney spam)</li></ul>'); // Disable maintenance mode. \Drupal::state()->set('system.maintenance_mode', FALSE); // We finished updating so we can login the user now. $this->drupalLogin($this->rootUser); // The block that we are testing has the following visibility rules: // - only visible on node pages // - only visible to authenticated users. $block_title = 'Test for 2354889'; // Create two nodes, a page and an article. $page = Node::create(['type' => 'page', 'title' => 'Page node']); $page->save(); $article = Node::create(['type' => 'article', 'title' => 'Article node']); $article->save(); // Check that the block appears only on Page nodes for authenticated users. $this->drupalGet('node/' . $page->id()); $this->assertRaw($block_title, 'Test block is visible on a Page node as an authenticated user.'); $this->drupalGet('node/' . $article->id()); $this->assertNoRaw($block_title, 'Test block is not visible on a Article node as an authenticated user.'); $this->drupalLogout(); // Check that the block does not appear on any page for anonymous users. $this->drupalGet('node/' . $page->id()); $this->assertNoRaw($block_title, 'Test block is not visible on a Page node as an anonymous user.'); $this->drupalGet('node/' . $article->id()); $this->assertNoRaw($block_title, 'Test block is not visible on a Article node as an anonymous user.'); // Ensure that all the context mappings got updated properly. $block = Block::load('testfor2354889'); $visibility = $block->get('visibility'); $this->assertEqual('@node.node_route_context:node', $visibility['node_type']['context_mapping']['node']); $this->assertEqual('@user.current_user_context:current_user', $visibility['user_role']['context_mapping']['user']); $this->assertEqual('@language.current_language_context:language_interface', $visibility['language']['context_mapping']['language']); // Check that a block with invalid context is being disabled and that it can // still be edited afterward. $disabled_block = Block::load('thirdtestfor2354889'); $this->assertFalse($disabled_block->status(), 'Block with invalid context is disabled'); $this->assertEqual(['thirdtestfor2354889' => ['missing_context_ids' => ['baloney.spam' => ['node_type']], 'status' => TRUE]], \Drupal::keyValue('update_backup')->get('block_update_8001')); $disabled_block_visibility = $disabled_block->get('visibility'); $this->assertTrue(!isset($disabled_block_visibility['node_type']), 'The problematic visibility condition has been removed.'); $admin_user = $this->drupalCreateUser(['administer blocks']); $this->drupalLogin($admin_user); $this->drupalGet('admin/structure/block/manage/thirdtestfor2354889'); $this->assertResponse('200'); }
/** * Tests if the visibility settings are removed if the language is deleted. */ public function testLanguageBlockVisibilityLanguageDelete() { // Enable a standard block and set the visibility setting for one language. $edit = array('visibility' => array('language' => array('language_type' => 'language_interface', 'langcodes' => array('fr' => 'fr')))); $block = $this->drupalPlaceBlock('system_powered_by_block', $edit); // Check that we have the language in config after saving the setting. $visibility = $block->getVisibility(); $language = $visibility['language']['langcodes']['fr']; $this->assertTrue('fr' === $language, 'Language is set in the block configuration.'); // Delete the language. $this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete')); // Check that the language is no longer stored in the configuration after // it is deleted. $block = Block::load($block->id()); $visibility = $block->getVisibility(); $this->assertTrue(empty($visibility['language']['langcodes']['fr']), 'Language is no longer not set in the block configuration after deleting the block.'); }
/** * Asserts various aspects of a block. * * @param string $id * The block ID. * @param string $plugin_id * The block's plugin ID. * @param array $roles * Role IDs the block is expected to have. * @param string $pages * The list of pages on which the block should appear. * @param string $region * The display region. * @param string $theme * The theme. * @param string $weight * The block weight. */ public function assertEntity($id, $plugin_id, array $roles, $pages, $region, $theme, $weight) { $block = Block::load($id); $this->assertTrue($block instanceof Block); /** @var \Drupal\block\BlockInterface $block */ $this->assertIdentical($plugin_id, $block->getPluginId()); $visibility = $block->getVisibility(); if ($roles) { $this->assertIdentical($roles, array_values($visibility['user_role']['roles'])); $this->assertIdentical('@user.current_user_context:current_user', $visibility['user_role']['context_mapping']['user']); } if ($pages) { $this->assertIdentical($pages, $visibility['request_path']['pages']); } $this->assertIdentical($region, $block->getRegion()); $this->assertIdentical($theme, $block->getTheme()); $this->assertIdentical($weight, $block->getWeight()); }
/** * Tests hook invocations for CRUD operations on blocks. */ public function testBlockHooks() { $entity = entity_create('block', array('id' => 'stark_test_html', 'plugin' => 'test_html', 'theme' => 'stark')); $this->assertHookMessageOrder(array('entity_crud_hook_test_block_create called', 'entity_crud_hook_test_entity_create called for type block')); $GLOBALS['entity_crud_hook_test'] = array(); $entity->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_block_presave called', 'entity_crud_hook_test_entity_presave called for type block', 'entity_crud_hook_test_block_insert called', 'entity_crud_hook_test_entity_insert called for type block')); $GLOBALS['entity_crud_hook_test'] = array(); $entity = Block::load($entity->id()); $this->assertHookMessageOrder(array('entity_crud_hook_test_entity_load called for type block', 'entity_crud_hook_test_block_load called')); $GLOBALS['entity_crud_hook_test'] = array(); $entity->label = 'New label'; $entity->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_block_presave called', 'entity_crud_hook_test_entity_presave called for type block', 'entity_crud_hook_test_block_update called', 'entity_crud_hook_test_entity_update called for type block')); $GLOBALS['entity_crud_hook_test'] = array(); $entity->delete(); $this->assertHookMessageOrder(array('entity_crud_hook_test_block_predelete called', 'entity_crud_hook_test_entity_predelete called for type block', 'entity_crud_hook_test_block_delete called', 'entity_crud_hook_test_entity_delete called for type block')); }
/** * {@inheritdoc} */ public function process($text, $langcode) { $new_text = $text; $filter_result = new FilterProcessResult($text); if (preg_match('/\\[survey\\:.+\\]/', $text, $result)) { $token = $result[0]; $start = strpos($token, ':') + 1; $length = strpos($token, ']') - $start; $id = substr($token, $start, $length); $block = Block::load($id); if ($block) { $replace = $block->get('settings')['html']; $new_text = str_replace($token, $replace, $text); $filter_result->setProcessedText($new_text); $filter_result->setCacheTags($block->getCacheTags()); } } return $filter_result; }
/** * Tests if the visibility settings are removed if the language is deleted. */ public function testLanguageBlockVisibilityLanguageDelete() { // Enable a standard block and set the visibility setting for one language. $edit = array('visibility' => array('language' => array('langcodes' => array('fr' => 'fr')))); $block = $this->drupalPlaceBlock('system_powered_by_block', $edit); // Check that we have the language in config after saving the setting. $visibility = $block->getVisibility(); $this->assertEqual('fr', $visibility['language']['langcodes']['fr'], 'Language is set in the block configuration.'); // Delete the language. $this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete')); // Check that the language is no longer stored in the configuration after // it is deleted. $block = Block::load($block->id()); $visibility = $block->getVisibility(); $this->assertTrue(empty($visibility['language']['langcodes']['fr']), 'Language is no longer not set in the block configuration after deleting the block.'); // Ensure that the block visibility for language is gone from the UI. $this->drupalGet('admin/structure/block'); $this->clickLink('Configure'); $elements = $this->xpath('//details[@id="edit-visibility-language"]'); $this->assertTrue(empty($elements)); }
/** * Tests that blocks assigned to invalid regions work correctly. */ function testBlockInInvalidRegion() { // Enable a test block and place it in an invalid region. $block = $this->drupalPlaceBlock('test_html'); $block->setRegion('invalid_region'); $block->save(); $warning_message = t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block->id(), '%region' => 'invalid_region')); // Clearing the cache should disable the test block placed in the invalid region. $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); $this->assertRaw($warning_message, 'Enabled block was in the invalid region and has been disabled.'); // Clear the cache to check if the warning message is not triggered. $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.'); // Place disabled test block in the invalid region of the default theme. $block = Block::load($block->id()); $block->setRegion('invalid_region'); $block->save(); // Clear the cache to check if the warning message is not triggered. $this->drupalPostForm('admin/config/development/performance', array(), 'Clear all caches'); $this->assertNoRaw($warning_message, 'Disabled block in the invalid region will not trigger the warning.'); }
/** * Asserts various aspects of a block. * * @param string $id * The block ID. * @param string $plugin_id * The block's plugin ID. * @param array $roles * Role IDs the block is expected to have. * @param string $pages * The list of pages on which the block should appear. * @param string $region * The display region. * @param string $theme * The theme. * @param string $weight * The block weight. * @param string $label * The block label. * @param string $label_display * The block label display setting. * @param bool $status * (optional) Whether the block is expected to be enabled. */ public function assertEntity($id, $plugin_id, array $roles, $pages, $region, $theme, $weight, $label, $label_display, $status = TRUE) { $block = Block::load($id); $this->assertTrue($block instanceof Block); /** @var \Drupal\block\BlockInterface $block */ $this->assertSame($plugin_id, $block->getPluginId()); $visibility = $block->getVisibility(); if ($roles) { $this->assertSame($roles, array_values($visibility['user_role']['roles'])); $this->assertSame('@user.current_user_context:current_user', $visibility['user_role']['context_mapping']['user']); } if ($pages) { $this->assertSame($pages, $visibility['request_path']['pages']); } $this->assertSame($region, $block->getRegion()); $this->assertSame($theme, $block->getTheme()); $this->assertSame($weight, $block->getWeight()); $this->assertSame($status, $block->status()); $config = $this->config('block.block.' . $id); $this->assertSame($label, $config->get('settings.label')); $this->assertSame($label_display, $config->get('settings.label_display')); }
/** * Tests menu block settings. */ protected function doTestMenuBlock() { $menu_id = $this->menu->id(); $block_id = $this->blockPlacements[$menu_id]; $this->drupalGet('admin/structure/block/manage/' . $block_id); $this->drupalPostForm(NULL, ['settings[depth]' => 3, 'settings[level]' => 2], t('Save block')); $block = Block::load($block_id); $settings = $block->getPlugin()->getConfiguration(); $this->assertEqual($settings['depth'], 3); $this->assertEqual($settings['level'], 2); // Reset settings. $block->getPlugin()->setConfigurationValue('depth', 0); $block->getPlugin()->setConfigurationValue('level', 1); $block->save(); }
/** * Tests the recent comments block. */ public function testRecentNodeBlock() { $this->drupalLogin($this->adminUser); // Disallow anonymous users to view content. user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access content' => FALSE)); // Enable the recent content block with two items. $block = $this->drupalPlaceBlock('views_block:content_recent-block_1', array('id' => 'test_block', 'items_per_page' => 2)); // Test that block is not visible without nodes. $this->drupalGet(''); $this->assertText(t('No content available.'), 'Block with "No content available." found.'); // Add some test nodes. $default_settings = array('uid' => $this->webUser->id(), 'type' => 'article'); $node1 = $this->drupalCreateNode($default_settings); $node2 = $this->drupalCreateNode($default_settings); $node3 = $this->drupalCreateNode($default_settings); // Change the changed time for node so that we can test ordering. db_update('node_field_data')->fields(array('changed' => $node1->getChangedTime() + 100))->condition('nid', $node2->id())->execute(); db_update('node_field_data')->fields(array('changed' => $node1->getChangedTime() + 200))->condition('nid', $node3->id())->execute(); // Test that a user without the 'access content' permission cannot // see the block. $this->drupalLogout(); $this->drupalGet(''); $this->assertNoText($block->label(), 'Block was not found.'); // Test that only the 2 latest nodes are shown. $this->drupalLogin($this->webUser); $this->assertNoText($node1->label(), 'Node not found in block.'); $this->assertText($node2->label(), 'Node found in block.'); $this->assertText($node3->label(), 'Node found in block.'); // Check to make sure nodes are in the right order. $this->assertTrue($this->xpath('//div[@id="block-test-block"]//table/tbody/tr[position() = 1]/td/a[text() = "' . $node3->label() . '"]'), 'Nodes were ordered correctly in block.'); $this->drupalLogout(); $this->drupalLogin($this->adminUser); // Verify that the More link is shown and leads to the admin content page. $this->drupalGet(''); $this->clickLink('More'); $this->assertResponse('200'); $this->assertUrl('admin/content'); // Set the number of recent nodes to show to 10. $block->getPlugin()->setConfigurationValue('items_per_page', 10); $block->save(); // Post an additional node. $node4 = $this->drupalCreateNode($default_settings); // Test that all four nodes are shown. $this->drupalGet(''); $this->assertText($node1->label(), 'Node found in block.'); $this->assertText($node2->label(), 'Node found in block.'); $this->assertText($node3->label(), 'Node found in block.'); $this->assertText($node4->label(), 'Node found in block.'); // Enable the "Powered by Drupal" block only on article nodes. $edit = ['id' => strtolower($this->randomMachineName()), 'region' => 'sidebar_first', 'visibility[node_type][bundles][article]' => 'article']; $theme = \Drupal::service('theme_handler')->getDefault(); $this->drupalPostForm("admin/structure/block/add/system_powered_by_block/{$theme}", $edit, t('Save block')); $block = Block::load($edit['id']); $visibility = $block->getVisibility(); $this->assertTrue(isset($visibility['node_type']['bundles']['article']), 'Visibility settings were saved to configuration'); // Create a page node. $node5 = $this->drupalCreateNode(array('uid' => $this->adminUser->id(), 'type' => 'page')); $this->drupalLogout(); $this->drupalLogin($this->webUser); // Verify visibility rules. $this->drupalGet(''); $label = $block->label(); $this->assertNoText($label, 'Block was not displayed on the front page.'); $this->drupalGet('node/add/article'); $this->assertText($label, 'Block was displayed on the node/add/article page.'); $this->drupalGet('node/' . $node1->id()); $this->assertText($label, 'Block was displayed on the node/N when node is of type article.'); $this->drupalGet('node/' . $node5->id()); $this->assertNoText($label, 'Block was not displayed on nodes of type page.'); $this->drupalLogin($this->adminUser); $this->drupalGet('admin/structure/block'); $this->assertText($label, 'Block was displayed on the admin/structure/block page.'); $this->assertLinkByHref($block->url()); }
/** * Replacing value for field entity reference * * @param $crawler, $field_name, $field, $entity * crawler object * field name * field array * entity * * @return * render crawler object/render markup after replacing value */ public function findAndReplaceEntityReference($crawler, $field_name, $field, $entity) { $entity_type = $entity->getEntityTypeId(); $bundle = $entity->bundle(); $field_instance = FieldConfig::loadByName($entity_type, $bundle, $bundle . '_' . $field_name); $settings = $field_instance->getSettings(); switch ($settings['handler']) { case 'default:view': $view_render_array = views_embed_view($field['target_id']); $crawler->filter('[data-field="' . $field_name . '"]')->append(drupal_render($view_render_array)->__toString()); break; case 'default:block': $block = \Drupal\block\Entity\Block::load($field['target_id']); $block_content = \Drupal::entityManager()->getViewBuilder('block')->view($block); $crawler->filter('[data-field="' . $field_name . '"]')->append(drupal_render($block_content)->__toString()); break; case 'default:contact_form': $form_id = $field['content']['target_id']; $message = \Drupal::entityManager()->getStorage('contact_message')->create(array('contact_form' => $form_id)); $render_markup = \Drupal::service('entity.form_builder')->getForm($message); $markup = drupal_render($render_markup); $crawler->filter('[data-field="' . $field_name . '"]')->replaceWith($markup->__toString()); break; default: break; } }
/** * Tests if the language switcher block gets deleted when a language type has been made not configurable. */ public function testDisableLanguageSwitcher() { $block_id = 'test_language_block'; // Enable the language switcher block. $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, array('id' => $block_id)); // Check if the language switcher block has been created. $block = Block::load($block_id); $this->assertTrue($block, 'Language switcher block was created.'); // Make sure language_content is not configurable. $edit = array('language_content[configurable]' => FALSE); $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings')); $this->assertResponse(200); // Check if the language switcher block has been removed. $block = Block::load($block_id); $this->assertFalse($block, 'Language switcher block was removed.'); }
/** * Tests the block migration. */ public function testBlockMigration() { $blocks = Block::loadMultiple(); $this->assertIdentical(9, count($blocks)); // User blocks $visibility = []; $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = TRUE; $visibility['request_path']['pages'] = "<front>\n/node/1\n/blog/*"; $this->assertEntity('user', $visibility, 'sidebar_first', 'bartik', 0); $visibility = []; $this->assertEntity('user_1', $visibility, 'sidebar_first', 'bartik', 0); $visibility['user_role']['id'] = 'user_role'; $roles['authenticated'] = 'authenticated'; $visibility['user_role']['roles'] = $roles; $context_mapping['user'] = '******'; $visibility['user_role']['context_mapping'] = $context_mapping; $visibility['user_role']['negate'] = FALSE; $this->assertEntity('user_2', $visibility, 'sidebar_second', 'bartik', -9); $visibility = []; $visibility['user_role']['id'] = 'user_role'; $visibility['user_role']['roles'] = ['migrate_test_role_1' => 'migrate_test_role_1']; $context_mapping['user'] = '******'; $visibility['user_role']['context_mapping'] = $context_mapping; $visibility['user_role']['negate'] = FALSE; $this->assertEntity('user_3', $visibility, 'sidebar_second', 'bartik', -6); // Check system block $visibility = []; $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = TRUE; $visibility['request_path']['pages'] = '/node/1'; $this->assertEntity('system', $visibility, 'footer', 'bartik', -5); // Check menu blocks $visibility = []; $this->assertEntity('menu', $visibility, 'header', 'bartik', -5); // Check custom blocks $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = FALSE; $visibility['request_path']['pages'] = '<front>'; $this->assertEntity('block', $visibility, 'content', 'bartik', 0); $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = FALSE; $visibility['request_path']['pages'] = '/node'; $this->assertEntity('block_1', $visibility, 'sidebar_second', 'bluemarine', -4); $visibility = []; $this->assertEntity('block_2', $visibility, 'right', 'test_theme', -7); // Custom block with php code is not migrated. $block = Block::load('block_3'); $this->assertFalse($block instanceof Block); }
/** * #lazy_builder callback; builds a #pre_render-able block. * * @param $entity_id * A block config entity ID. * @param $view_mode * The view mode the block is being viewed in. * * @return array * A render array with a #pre_render callback to render the block. */ public static function lazyBuilder($entity_id, $view_mode) { return static::buildPreRenderableBlock(Block::load($entity_id), \Drupal::service('module_handler')); }
/** * Gets the HTML markup for a block by it's ID. * * @param $sBlockId The id of the block as string. * * @return string The HTML markup for the rendered block. */ private function getBlockMarkupById($sBlockId) { $oBlock = \Drupal\block\Entity\Block::load($sBlockId); $aRenderArray = \Drupal::entityManager()->getViewBuilder('block')->view($oBlock); return \Drupal::service('renderer')->render($aRenderArray); }
/** * Tests block_user_role_delete. */ public function testBlockUserRoleDelete() { $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]); $role1->save(); $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]); $role2->save(); $block = Block::create(['id' => $this->randomMachineName(), 'plugin' => 'system_powered_by_block']); $block->setVisibilityConfig('user_role', ['roles' => [$role1->id() => $role1->id(), $role2->id() => $role2->id()]]); $block->save(); $this->assertEqual($block->getVisibility()['user_role']['roles'], [$role1->id() => $role1->id(), $role2->id() => $role2->id()]); $role1->delete(); $block = Block::load($block->id()); $this->assertEqual($block->getVisibility()['user_role']['roles'], [$role2->id() => $role2->id()]); }
/** * Tests that uninstalling a theme removes its block configuration. */ public function testUninstallTheme() { /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */ $theme_handler = \Drupal::service('theme_handler'); $theme_handler->install(['seven']); $theme_handler->setDefault('seven'); $block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']); $this->drupalGet('<front>'); $this->assertText('Powered by Drupal'); $theme_handler->setDefault('classy'); $theme_handler->uninstall(['seven']); // Ensure that the block configuration does not exist anymore. $this->assertIdentical(NULL, Block::load($block->id())); }
/** * Tests the block migration. */ public function testBlockMigration() { $blocks = Block::loadMultiple(); $this->assertIdentical(9, count($blocks)); // User blocks $visibility = []; $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = TRUE; $visibility['request_path']['pages'] = "<front>\n/node/1\n/blog/*"; $this->assertEntity('user', $visibility, 'sidebar_first', 'bartik', 0, '', '0'); $visibility = []; $this->assertEntity('user_1', $visibility, 'sidebar_first', 'bartik', 0, '', '0'); $visibility['user_role']['id'] = 'user_role'; $roles['authenticated'] = 'authenticated'; $visibility['user_role']['roles'] = $roles; $context_mapping['user'] = '******'; $visibility['user_role']['context_mapping'] = $context_mapping; $visibility['user_role']['negate'] = FALSE; $this->assertEntity('user_2', $visibility, 'sidebar_second', 'bartik', -9, '', '0'); $visibility = []; $visibility['user_role']['id'] = 'user_role'; $visibility['user_role']['roles'] = ['migrate_test_role_1' => 'migrate_test_role_1']; $context_mapping['user'] = '******'; $visibility['user_role']['context_mapping'] = $context_mapping; $visibility['user_role']['negate'] = FALSE; $this->assertEntity('user_3', $visibility, 'sidebar_second', 'bartik', -6, '', '0'); // Check system block $visibility = []; $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = TRUE; $visibility['request_path']['pages'] = '/node/1'; $this->assertEntity('system', $visibility, 'footer_fifth', 'bartik', -5, '', '0'); // Check menu blocks $visibility = []; $this->assertEntity('menu', $visibility, 'header', 'bartik', -5, '', '0'); // Check custom blocks $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = FALSE; $visibility['request_path']['pages'] = '<front>'; $this->assertEntity('block', $visibility, 'content', 'bartik', 0, 'Static Block', 'visible'); $visibility['request_path']['id'] = 'request_path'; $visibility['request_path']['negate'] = FALSE; $visibility['request_path']['pages'] = '/node'; // bluemarine does not exist in Drupal 8 and the d6_block migration defines // no mapping for its regions, so this block should have been defaulted // to the 'content' region. $this->assertEntity('block_1', $visibility, 'content', 'bluemarine', -4, 'Another Static Block', 'visible'); $visibility = []; $this->assertEntity('block_2', $visibility, 'right', 'test_theme', -7, '', '0'); // Custom block with php code is not migrated. $block = Block::load('block_3'); $this->assertFalse($block instanceof Block); }
/** * Test newsletter subscription management. * * Steps performed: */ function testSubscriptionManagement() { $admin_user = $this->drupalCreateUser(array('administer newsletters', 'administer simplenews settings', 'administer simplenews subscriptions', 'administer users')); $this->drupalLogin($admin_user); // Create a newsletter. $newsletter_name = Unicode::strtolower($this->randomMachineName()); $edit = array('name' => $newsletter_name, 'id' => $newsletter_name); $this->drupalPostForm('admin/config/services/simplenews/add', $edit, t('Save')); // Add a number of users to each newsletter separately and then add another // bunch to both. $subscribers = array(); $groups = array(); $newsletters = simplenews_newsletter_get_all(); foreach ($newsletters as $newsletter) { $groups[$newsletter->id()] = array($newsletter->id()); } $groups['all'] = array_keys($groups); $subscribers_flat = array(); foreach ($groups as $key => $group) { for ($i = 0; $i < 5; $i++) { $mail = $this->randomEmail(); $subscribers[$key][$mail] = $mail; $subscribers_flat[$mail] = $mail; } } // Create a user and assign him one of the mail addresses of the all group. $user = $this->drupalCreateUser(array('subscribe to newsletters')); // Make sure that user_save() does not update the user object, as it will // override the pass_raw property which we'll need to log this user in // later on. $user_mail = current($subscribers['all']); $user->setEmail($user_mail); $user->save(); $delimiters = array(',', ' ', "\n"); // Visit subscribers by clicking menu tab in people. $this->drupalGet('admin/people'); $this->clickLink('Subscribers'); $i = 0; foreach ($groups as $key => $group) { $this->clickLink(t('Mass subscribe')); $edit = array('emails' => implode($delimiters[$i++], $subscribers[$key])); foreach ($group as $newsletter_id) { $edit['newsletters[' . $newsletter_id . ']'] = TRUE; } $this->drupalPostForm(NULL, $edit, t('Subscribe')); } // The user to which the mail was assigned should be listed too. $this->assertText($user->label()); // Verify that all addresses are displayed in the table. $rows = $this->xpath('//tbody/tr'); $mail_addresses = array(); for ($i = 0; $i < count($subscribers_flat); $i++) { $mail_addresses[] = trim((string) $rows[$i]->td[0]); } $this->assertEqual(15, count($mail_addresses)); foreach ($mail_addresses as $mail_address) { $mail_address = (string) $mail_address; $this->assertTrue(isset($subscribers_flat[$mail_address])); unset($subscribers_flat[$mail_address]); } // All entries of the array should be removed by now. $this->assertTrue(empty($subscribers_flat)); reset($groups); $first = 'default'; $first_mail = array_rand($subscribers[$first]); $all_mail = array_rand($subscribers['all']); // Limit list to subscribers of the first newsletter only. // Build a flat list of the subscribers of this list. $subscribers_flat = array_merge($subscribers[$first], $subscribers['all']); $this->drupalGet('admin/people/simplenews', array('query' => array('subscriptions_target_id' => $first))); // Verify that all addresses are displayed in the table. $rows = $this->xpath('//tbody/tr'); $mail_addresses = array(); for ($i = 0; $i < count($subscribers_flat); $i++) { $mail_addresses[] = trim((string) $rows[$i]->td[0]); } $this->assertEqual(10, count($mail_addresses)); foreach ($mail_addresses as $mail_address) { $mail_address = (string) $mail_address; $this->assertTrue(isset($subscribers_flat[$mail_address])); unset($subscribers_flat[$mail_address]); } // All entries of the array should be removed by now. $this->assertTrue(empty($subscribers_flat)); // Filter a single mail address, the one assigned to a user. $edit = array('mail' => Unicode::substr(current($subscribers['all']), 0, 4)); $this->drupalGet('admin/people/simplenews', array('query' => array('mail' => $edit['mail']))); $rows = $this->xpath('//tbody/tr'); $this->assertEqual(1, count($rows)); $this->assertEqual(current($subscribers['all']), trim((string) $rows[0]->td[0])); $this->assertEqual($user->label(), trim((string) $rows[0]->td[1]->span)); // Reset the filter. $this->drupalGet('admin/people/simplenews'); // Test mass-unsubscribe, unsubscribe one from the first group and one from // the all group, but only from the first newsletter. unset($subscribers[$first][$first_mail]); $edit = array('emails' => $first_mail . ', ' . $all_mail, 'newsletters[' . $first . ']' => TRUE); $this->clickLink(t('Mass unsubscribe')); $this->drupalPostForm(NULL, $edit, t('Unsubscribe')); // The all mail is still displayed because it's still subscribed to the // second newsletter. Reload the page to get rid of the confirmation // message. $this->drupalGet('admin/people/simplenews'); $this->assertNoText($first_mail); $this->assertText($all_mail); // Limit to first newsletter, the all mail shouldn't be shown anymore. $this->drupalGet('admin/people/simplenews', array('query' => array('subscriptions_target_id' => $first))); $this->assertNoText($first_mail); $this->assertNoText($all_mail); // Check exporting. $this->clickLink(t('Export')); $this->drupalPostForm(NULL, array('newsletters[' . $first . ']' => TRUE), t('Export')); $export_field = $this->xpath($this->constructFieldXpath('name', 'emails')); $exported_mails = (string) $export_field[0]; foreach ($subscribers[$first] as $mail) { $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.')); } foreach ($subscribers['all'] as $mail) { if ($mail != $all_mail) { $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.')); } else { $this->assertFALSE(strpos($exported_mails, $mail) !== FALSE, t('Unsubscribed mail address not exported.')); } } // Only export unsubscribed mail addresses. $edit = array('subscribed[subscribed]' => FALSE, 'subscribed[unsubscribed]' => TRUE, 'newsletters[' . $first . ']' => TRUE); $this->drupalPostForm(NULL, $edit, t('Export')); $export_field = $this->xpath($this->constructFieldXpath('name', 'emails')); $exported_mails = (string) $export_field[0]; $exported_mails = explode(', ', $exported_mails); $this->assertEqual(2, count($exported_mails)); $this->assertTrue(in_array($all_mail, $exported_mails)); $this->assertTrue(in_array($first_mail, $exported_mails)); /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */ $subscription_manager = \Drupal::service('simplenews.subscription_manager'); // Make sure there are unconfirmed subscriptions. $unconfirmed = array(); $unconfirmed[] = $this->randomEmail(); $unconfirmed[] = $this->randomEmail(); foreach ($unconfirmed as $mail) { $subscription_manager->subscribe($mail, $first, TRUE); } // Only export unconfirmed mail addresses. $edit = array('subscribed[subscribed]' => FALSE, 'subscribed[unconfirmed]' => TRUE, 'subscribed[unsubscribed]' => FALSE, 'newsletters[' . $first . ']' => TRUE); $this->drupalPostForm(NULL, $edit, t('Export')); $export_field = $this->xpath($this->constructFieldXpath('name', 'emails')); $exported_mails = (string) $export_field[0]; $exported_mails = explode(', ', $exported_mails); $this->assertEqual(2, count($exported_mails)); $this->assertTrue(in_array($unconfirmed[0], $exported_mails)); $this->assertTrue(in_array($unconfirmed[1], $exported_mails)); // Make sure the user is subscribed to the first newsletter_id. $subscription_manager->subscribe($user_mail, $first, FALSE); $before_count = simplenews_count_subscriptions($first); // Block the user. $user->block(); $user->save(); $this->drupalGet('admin/people/simplenews'); // Verify updated subscriptions count. drupal_static_reset('simplenews_count_subscriptions'); $after_count = simplenews_count_subscriptions($first); $this->assertEqual($before_count - 1, $after_count, t('Blocked users are not counted in subscription count.')); // Test mass subscribe with previously unsubscribed users. for ($i = 0; $i < 3; $i++) { $tested_subscribers[] = $this->randomEmail(); } $subscription_manager->subscribe($tested_subscribers[0], $first, FALSE); $subscription_manager->subscribe($tested_subscribers[1], $first, FALSE); $subscription_manager->unsubscribe($tested_subscribers[0], $first, FALSE); $subscription_manager->unsubscribe($tested_subscribers[1], $first, FALSE); $unsubscribed = implode(', ', array_slice($tested_subscribers, 0, 2)); $edit = array('emails' => implode(', ', $tested_subscribers), 'newsletters[' . $first . ']' => TRUE); $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe')); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $subscription_manager->reset(); $this->assertFalse($subscription_manager->isSubscribed($tested_subscribers[0], $first), t('Subscriber not resubscribed through mass subscription.')); $this->assertFalse($subscription_manager->isSubscribed($tested_subscribers[1], $first), t('Subscriber not resubscribed through mass subscription.')); $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[2], $first), t('Subscriber subscribed through mass subscription.')); $substitutes = array('@name' => SafeMarkup::checkPlain(simplenews_newsletter_load($first)->label()), '@mail' => $unsubscribed); $this->assertText(t('The following addresses were skipped because they have previously unsubscribed from @name: @mail.', $substitutes)); $this->assertText(t("If you would like to resubscribe them, use the 'Force resubscription' option.")); // Try to mass subscribe without specifying newsletters. $tested_subscribers[2] = $this->randomEmail(); $edit = array('emails' => implode(', ', $tested_subscribers), 'resubscribe' => TRUE); $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe')); $this->assertText('Subscribe to field is required.'); // Test mass subscribe with previously unsubscribed users and force // resubscription. $tested_subscribers[2] = $this->randomEmail(); $edit = array('emails' => implode(', ', $tested_subscribers), 'newsletters[' . $first . ']' => TRUE, 'resubscribe' => TRUE); $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe')); $subscription_manager->reset(); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[0], $first, t('Subscriber resubscribed trough mass subscription.'))); $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[1], $first, t('Subscriber resubscribed trough mass subscription.'))); $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[2], $first, t('Subscriber subscribed trough mass subscription.'))); // Try to mass unsubscribe without specifying newsletters. $tested_subscribers[2] = $this->randomEmail(); $edit = array('emails' => implode(', ', $tested_subscribers)); $this->drupalPostForm('admin/people/simplenews/unsubscribe', $edit, t('Unsubscribe')); $this->assertText('Unsubscribe from field is required.'); // Create two blocks, to ensure that they are updated/deleted when a // newsletter is deleted. $only_first_block = $this->setupSubscriptionBlock(['newsletters' => [$first]]); $all_block = $this->setupSubscriptionBlock(['newsletters' => array_keys($groups)]); $enabled_newsletters = $all_block->get('settings')['newsletters']; $this->assertTrue(in_array($first, $enabled_newsletters)); // Delete newsletter. \Drupal::entityManager()->getStorage('simplenews_newsletter')->resetCache(); $this->drupalGet('admin/config/services/simplenews/manage/' . $first); $this->clickLink(t('Delete')); $this->drupalPostForm(NULL, array(), t('Delete')); $this->assertText(t('All subscriptions to newsletter @newsletter have been deleted.', array('@newsletter' => $newsletters[$first]->name))); // Verify that all related data has been deleted/updated. $this->assertNull(Newsletter::load($first)); $this->assertNull(Block::load($only_first_block->id())); $all_block = Block::load($all_block->id()); $enabled_newsletters = $all_block->get('settings')['newsletters']; $this->assertFalse(in_array($first, $enabled_newsletters)); // Verify that all subscriptions of that newsletter have been removed. $this->drupalGet('admin/people/simplenews'); foreach ($subscribers[$first] as $mail) { $this->assertNoText($mail); } $this->clickLink(t('Edit'), 1); // Get the subscriber id from the path. $this->assertTrue(preg_match('|admin/people/simplenews/edit/(\\d+)\\?destination|', $this->getUrl(), $matches), 'Subscriber found'); $subscriber = Subscriber::load($matches[1]); $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal'); $this->assertFieldChecked('edit-status'); // Disable account. $edit = array('status' => FALSE); $this->drupalPostForm(NULL, $edit, t('Save')); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $subscription_manager->reset(); $this->assertFalse($subscription_manager->isSubscribed($subscriber->getMail(), $this->getRandomNewsletter()), t('Subscriber is not active')); // Re-enable account. $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id()); $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal'); $this->assertNoFieldChecked('edit-status'); $edit = array('status' => TRUE); $this->drupalPostForm(NULL, $edit, t('Save')); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $subscription_manager->reset(); $this->assertTrue($subscription_manager->isSubscribed($subscriber->getMail(), $this->getRandomNewsletter()), t('Subscriber is active again.')); // Remove the newsletter. $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id()); $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal'); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $subscriber = Subscriber::load($subscriber->id()); $nlids = $subscriber->getSubscribedNewsletterIds(); // If the subscriber still has subscribed to newsletter, try to unsubscribe. $newsletter_id = reset($nlids); $edit['subscriptions[' . $newsletter_id . ']'] = FALSE; $this->drupalPostForm(NULL, $edit, t('Save')); \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache(); $subscription_manager->reset(); $nlids = $subscriber->getSubscribedNewsletterIds(); $this->assertFalse($subscription_manager->isSubscribed($subscriber->getMail(), reset($nlids)), t('Subscriber not subscribed anymore.')); // @todo Test Admin subscriber edit preferred language $subscription->language // Register a subscriber with an insecure e-mail address through the API // and make sure the address is correctly encoded. $xss_mail = "<script>alert('XSS');</script>"; $subscription_manager->subscribe($xss_mail, $this->getRandomNewsletter(), FALSE); $this->drupalGet('admin/people/simplenews'); $this->assertNoRaw($xss_mail); $this->assertRaw(SafeMarkup::checkPlain($xss_mail)); $xss_subscriber = simplenews_subscriber_load_by_mail($xss_mail); $this->drupalGet('admin/people/simplenews/edit/' . $xss_subscriber->id()); $this->assertNoRaw($xss_mail); $this->assertRaw(SafeMarkup::checkPlain($xss_mail)); // Create a new user for the next test. $new_user = $this->drupalCreateUser(array('subscribe to newsletters')); // Test for saving the subscription for no newsletter. $this->drupalPostForm('user/' . $new_user->id() . '/simplenews', null, t('Save')); $this->assertText('The newsletter subscriptions for user ' . $new_user->getUsername() . ' have been updated.'); // Editing a subscriber with subscription. $edit = array('subscriptions[' . $newsletter_name . ']' => TRUE, 'status' => TRUE, 'mail[0][value]' => '*****@*****.**'); $this->drupalPostForm('admin/people/simplenews/edit/' . $xss_subscriber->id(), $edit, t('Save')); $this->assertText('Subscriber edit@example.com has been updated.'); // Create a second newsletter. $second_newsletter_name = Unicode::strtolower($this->randomMachineName()); $edit2 = array('name' => $second_newsletter_name, 'id' => $second_newsletter_name); $this->drupalPostForm('admin/config/services/simplenews/add', $edit2, t('Save')); // Test for adding a subscriber. $subscribe = array('newsletters[' . $newsletter_name . ']' => TRUE, 'emails' => '*****@*****.**'); $this->drupalPostForm('admin/people/simplenews/import', $subscribe, t('Subscribe')); // The subscriber should appear once in the list. $rows = $this->xpath('//tbody/tr'); $counter = 0; foreach ($rows as $value) { if (trim((string) $value->td[0]) == '*****@*****.**') { $counter++; } } $this->assertEqual(1, $counter); $this->assertText(t('The following addresses were added or updated: @email.', ['@email' => '*****@*****.**'])); $this->assertText(t('The addresses were subscribed to the following newsletters: @newsletter.', ['@newsletter' => $newsletter_name])); // Check exact subscription statuses. $subscriber = simplenews_subscriber_load_by_mail('*****@*****.**'); $this->assertEqual($subscriber->getSubscription($newsletter_name)->get('status')->getValue(), SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED); // The second newsletter was not subscribed, so there should be no // subscription record at all. $this->assertFalse($subscriber->getSubscription($second_newsletter_name)); }