Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / block / tests / src / Functional / BlockTest.php
1 <?php
2
3 namespace Drupal\Tests\block\Functional;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\block\Entity\Block;
7 use Drupal\Core\Url;
8 use Drupal\user\Entity\Role;
9 use Drupal\user\RoleInterface;
10
11 /**
12  * Tests basic block functionality.
13  *
14  * @group block
15  */
16 class BlockTest extends BlockTestBase {
17
18   /**
19    * Tests block visibility.
20    */
21   public function testBlockVisibility() {
22     $block_name = 'system_powered_by_block';
23     // Create a random title for the block.
24     $title = $this->randomMachineName(8);
25     // Enable a standard block.
26     $default_theme = $this->config('system.theme')->get('default');
27     $edit = [
28       'id' => strtolower($this->randomMachineName(8)),
29       'region' => 'sidebar_first',
30       'settings[label]' => $title,
31       'settings[label_display]' => TRUE,
32     ];
33     // Set the block to be hidden on any user path, and to be shown only to
34     // authenticated users.
35     $edit['visibility[request_path][pages]'] = '/user*';
36     $edit['visibility[request_path][negate]'] = TRUE;
37     $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
38     $this->drupalGet('admin/structure/block/add/' . $block_name . '/' . $default_theme);
39     $this->assertFieldChecked('edit-visibility-request-path-negate-0');
40
41     $this->drupalPostForm(NULL, $edit, t('Save block'));
42     $this->assertText('The block configuration has been saved.', 'Block was saved');
43
44     $this->clickLink('Configure');
45     $this->assertFieldChecked('edit-visibility-request-path-negate-1');
46
47     $this->drupalGet('');
48     $this->assertText($title, 'Block was displayed on the front page.');
49
50     $this->drupalGet('user');
51     $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
52
53     // Confirm that the block is not displayed to anonymous users.
54     $this->drupalLogout();
55     $this->drupalGet('');
56     $this->assertNoText($title, 'Block was not displayed to anonymous users.');
57
58     // Confirm that an empty block is not displayed.
59     $this->assertNoText('Powered by Drupal', 'Empty block not displayed.');
60     $this->assertNoRaw('sidebar-first', 'Empty sidebar-first region is not displayed.');
61   }
62
63   /**
64    * Tests that visibility can be properly toggled.
65    */
66   public function testBlockToggleVisibility() {
67     $block_name = 'system_powered_by_block';
68     // Create a random title for the block.
69     $title = $this->randomMachineName(8);
70     // Enable a standard block.
71     $default_theme = $this->config('system.theme')->get('default');
72     $edit = [
73       'id' => strtolower($this->randomMachineName(8)),
74       'region' => 'sidebar_first',
75       'settings[label]' => $title,
76     ];
77     $block_id = $edit['id'];
78     // Set the block to be shown only to authenticated users.
79     $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
80     $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
81     $this->clickLink('Configure');
82     $this->assertFieldChecked('edit-visibility-user-role-roles-authenticated');
83
84     $edit = [
85       'visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']' => FALSE,
86     ];
87     $this->drupalPostForm(NULL, $edit, 'Save block');
88     $this->clickLink('Configure');
89     $this->assertNoFieldChecked('edit-visibility-user-role-roles-authenticated');
90
91     // Ensure that no visibility is configured.
92     /** @var \Drupal\block\BlockInterface $block */
93     $block = Block::load($block_id);
94     $visibility_config = $block->getVisibilityConditions()->getConfiguration();
95     $this->assertIdentical([], $visibility_config);
96     $this->assertIdentical([], $block->get('visibility'));
97   }
98
99   /**
100    * Test block visibility when leaving "pages" textarea empty.
101    */
102   public function testBlockVisibilityListedEmpty() {
103     $block_name = 'system_powered_by_block';
104     // Create a random title for the block.
105     $title = $this->randomMachineName(8);
106     // Enable a standard block.
107     $default_theme = $this->config('system.theme')->get('default');
108     $edit = [
109       'id' => strtolower($this->randomMachineName(8)),
110       'region' => 'sidebar_first',
111       'settings[label]' => $title,
112       'visibility[request_path][negate]' => TRUE,
113     ];
114     // Set the block to be hidden on any user path, and to be shown only to
115     // authenticated users.
116     $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
117     $this->assertText('The block configuration has been saved.', 'Block was saved');
118
119     $this->drupalGet('user');
120     $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
121
122     $this->drupalGet('USER');
123     $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
124
125     // Confirm that the block is not displayed to anonymous users.
126     $this->drupalLogout();
127     $this->drupalGet('');
128     $this->assertNoText($title, 'Block was not displayed to anonymous users on the front page.');
129   }
130
131   /**
132    * Tests adding a block from the library page with a weight query string.
133    */
134   public function testAddBlockFromLibraryWithWeight() {
135     $default_theme = $this->config('system.theme')->get('default');
136     // Test one positive, zero, and one negative weight.
137     foreach (['7', '0', '-9'] as $weight) {
138       $options = [
139         'query' => [
140           'region' => 'sidebar_first',
141           'weight' => $weight,
142         ],
143       ];
144       $this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme], $options));
145
146       $block_name = 'system_powered_by_block';
147       $add_url = Url::fromRoute('block.admin_add', [
148         'plugin_id' => $block_name,
149         'theme' => $default_theme
150       ]);
151       $links = $this->xpath('//a[contains(@href, :href)]', [':href' => $add_url->toString()]);
152       $this->assertEqual(1, count($links), 'Found one matching link.');
153       $this->assertEqual(t('Place block'), $links[0]->getText(), 'Found the expected link text.');
154
155       list($path, $query_string) = explode('?', $links[0]->getAttribute('href'), 2);
156       parse_str($query_string, $query_parts);
157       $this->assertEqual($weight, $query_parts['weight'], 'Found the expected weight query string.');
158
159       // Create a random title for the block.
160       $title = $this->randomMachineName(8);
161       $block_id = strtolower($this->randomMachineName(8));
162       $edit = [
163         'id' => $block_id,
164         'settings[label]' => $title,
165       ];
166       // Create the block using the link parsed from the library page.
167       $this->drupalPostForm($this->getAbsoluteUrl($links[0]->getAttribute('href')), $edit, t('Save block'));
168
169       // Ensure that the block was created with the expected weight.
170       /** @var \Drupal\block\BlockInterface $block */
171       $block = Block::load($block_id);
172       $this->assertEqual($weight, $block->getWeight(), 'Found the block with expected weight.');
173     }
174   }
175
176   /**
177    * Test configuring and moving a module-define block to specific regions.
178    */
179   public function testBlock() {
180     // Place page title block to test error messages.
181     $this->drupalPlaceBlock('page_title_block');
182
183     // Disable the block.
184     $this->drupalGet('admin/structure/block');
185     $this->clickLink('Disable');
186
187     // Select the 'Powered by Drupal' block to be configured and moved.
188     $block = [];
189     $block['id'] = 'system_powered_by_block';
190     $block['settings[label]'] = $this->randomMachineName(8);
191     $block['settings[label_display]'] = TRUE;
192     $block['theme'] = $this->config('system.theme')->get('default');
193     $block['region'] = 'header';
194
195     // Set block title to confirm that interface works and override any custom titles.
196     $this->drupalPostForm('admin/structure/block/add/' . $block['id'] . '/' . $block['theme'], ['settings[label]' => $block['settings[label]'], 'settings[label_display]' => $block['settings[label_display]'], 'id' => $block['id'], 'region' => $block['region']], t('Save block'));
197     $this->assertText(t('The block configuration has been saved.'), 'Block title set.');
198     // Check to see if the block was created by checking its configuration.
199     $instance = Block::load($block['id']);
200
201     $this->assertEqual($instance->label(), $block['settings[label]'], 'Stored block title found.');
202
203     // Check whether the block can be moved to all available regions.
204     foreach ($this->regions as $region) {
205       $this->moveBlockToRegion($block, $region);
206     }
207
208     // Disable the block.
209     $this->drupalGet('admin/structure/block');
210     $this->clickLink('Disable');
211
212     // Confirm that the block is now listed as disabled.
213     $this->assertText(t('The block settings have been updated.'), 'Block successfully moved to disabled region.');
214
215     // Confirm that the block instance title and markup are not displayed.
216     $this->drupalGet('node');
217     $this->assertNoText(t($block['settings[label]']));
218     // Check for <div id="block-my-block-instance-name"> if the machine name
219     // is my_block_instance_name.
220     $xpath = $this->buildXPathQuery('//div[@id=:id]/*', [':id' => 'block-' . str_replace('_', '-', strtolower($block['id']))]);
221     $this->assertNoFieldByXPath($xpath, FALSE, 'Block found in no regions.');
222
223     // Test deleting the block from the edit form.
224     $this->drupalGet('admin/structure/block/manage/' . $block['id']);
225     $this->clickLink(t('Remove block'));
226     $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block['settings[label]']]));
227     $this->drupalPostForm(NULL, [], t('Remove'));
228     $this->assertRaw(t('The block %name has been removed.', ['%name' => $block['settings[label]']]));
229
230     // Test deleting a block via "Configure block" link.
231     $block = $this->drupalPlaceBlock('system_powered_by_block');
232     $this->drupalGet('admin/structure/block/manage/' . $block->id(), ['query' => ['destination' => 'admin']]);
233     $this->clickLink(t('Remove block'));
234     $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block->label()]));
235     $this->drupalPostForm(NULL, [], t('Remove'));
236     $this->assertRaw(t('The block %name has been removed.', ['%name' => $block->label()]));
237     $this->assertUrl('admin');
238     $this->assertNoRaw($block->id());
239   }
240
241   /**
242    * Tests that the block form has a theme selector when not passed via the URL.
243    */
244   public function testBlockThemeSelector() {
245     // Install all themes.
246     \Drupal::service('theme_handler')->install(['bartik', 'seven', 'stark']);
247     $theme_settings = $this->config('system.theme');
248     foreach (['bartik', 'seven', 'stark'] as $theme) {
249       $this->drupalGet('admin/structure/block/list/' . $theme);
250       $this->assertTitle(t('Block layout') . ' | Drupal');
251       // Select the 'Powered by Drupal' block to be placed.
252       $block = [];
253       $block['id'] = strtolower($this->randomMachineName());
254       $block['theme'] = $theme;
255       $block['region'] = 'content';
256       $this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
257       $this->assertText(t('The block configuration has been saved.'));
258       $this->assertUrl('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));
259
260       // Set the default theme and ensure the block is placed.
261       $theme_settings->set('default', $theme)->save();
262       $this->drupalGet('');
263       $elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]);
264       $this->assertTrue(!empty($elements), 'The block was found.');
265     }
266   }
267
268   /**
269    * Test block display of theme titles.
270    */
271   public function testThemeName() {
272     // Enable the help block.
273     $this->drupalPlaceBlock('help_block', ['region' => 'help']);
274     $this->drupalPlaceBlock('local_tasks_block');
275     // Explicitly set the default and admin themes.
276     $theme = 'block_test_specialchars_theme';
277     \Drupal::service('theme_handler')->install([$theme]);
278     \Drupal::service('router.builder')->rebuild();
279     $this->drupalGet('admin/structure/block');
280     $this->assertEscaped('<"Cat" & \'Mouse\'>');
281     $this->drupalGet('admin/structure/block/list/block_test_specialchars_theme');
282     $this->assertEscaped('Demonstrate block regions (<"Cat" & \'Mouse\'>)');
283   }
284
285   /**
286    * Test block title display settings.
287    */
288   public function testHideBlockTitle() {
289     $block_name = 'system_powered_by_block';
290     // Create a random title for the block.
291     $title = $this->randomMachineName(8);
292     $id = strtolower($this->randomMachineName(8));
293     // Enable a standard block.
294     $default_theme = $this->config('system.theme')->get('default');
295     $edit = [
296       'id' => $id,
297       'region' => 'sidebar_first',
298       'settings[label]' => $title,
299     ];
300     $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
301     $this->assertText('The block configuration has been saved.', 'Block was saved');
302
303     $this->drupalGet('user');
304     $this->assertNoText($title, 'Block title was not displayed by default.');
305
306     $edit = [
307       'settings[label_display]' => TRUE,
308     ];
309     $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
310     $this->assertText('The block configuration has been saved.', 'Block was saved');
311
312     $this->drupalGet('admin/structure/block/manage/' . $id);
313     $this->assertFieldChecked('edit-settings-label-display', 'The display_block option has the correct default value on the configuration form.');
314
315     $this->drupalGet('user');
316     $this->assertText($title, 'Block title was displayed when enabled.');
317   }
318
319   /**
320    * Moves a block to a given region via the UI and confirms the result.
321    *
322    * @param array $block
323    *   An array of information about the block, including the following keys:
324    *   - module: The module providing the block.
325    *   - title: The title of the block.
326    *   - delta: The block's delta key.
327    * @param string $region
328    *   The machine name of the theme region to move the block to, for example
329    *   'header' or 'sidebar_first'.
330    */
331   public function moveBlockToRegion(array $block, $region) {
332     // Set the created block to a specific region.
333     $block += ['theme' => $this->config('system.theme')->get('default')];
334     $edit = [];
335     $edit['blocks[' . $block['id'] . '][region]'] = $region;
336     $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
337
338     // Confirm that the block was moved to the proper region.
339     $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', ['%region_name' => $region]));
340
341     // Confirm that the block is being displayed.
342     $this->drupalGet('');
343     $this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.');
344
345     // Confirm that the custom block was found at the proper region.
346     $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [
347       ':region-class' => 'region region-' . Html::getClass($region),
348       ':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])),
349     ]);
350     $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)]));
351   }
352
353   /**
354    * Test that cache tags are properly set and bubbled up to the page cache.
355    *
356    * Verify that invalidation of these cache tags works:
357    * - "block:<block ID>"
358    * - "block_plugin:<block plugin ID>"
359    */
360   public function testBlockCacheTags() {
361     // The page cache only works for anonymous users.
362     $this->drupalLogout();
363
364     // Enable page caching.
365     $config = $this->config('system.performance');
366     $config->set('cache.page.max_age', 300);
367     $config->save();
368
369     // Place the "Powered by Drupal" block.
370     $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
371
372     // Prime the page cache.
373     $this->drupalGet('<front>');
374     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
375
376     // Verify a cache hit, but also the presence of the correct cache tags in
377     // both the page and block caches.
378     $this->drupalGet('<front>');
379     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
380     $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
381     $cid = implode(':', $cid_parts);
382     $cache_entry = \Drupal::cache('page')->get($cid);
383     $expected_cache_tags = [
384       'config:block_list',
385       'block_view',
386       'config:block.block.powered',
387       'config:user.role.anonymous',
388       'http_response',
389       'rendered',
390     ];
391     sort($expected_cache_tags);
392     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
393     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
394     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
395     $expected_cache_tags = [
396       'block_view',
397       'config:block.block.powered',
398       'rendered',
399     ];
400     sort($expected_cache_tags);
401     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
402
403     // The "Powered by Drupal" block is modified; verify a cache miss.
404     $block->setRegion('content');
405     $block->save();
406     $this->drupalGet('<front>');
407     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
408
409     // Now we should have a cache hit again.
410     $this->drupalGet('<front>');
411     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
412
413     // Place the "Powered by Drupal" block another time; verify a cache miss.
414     $block_2 = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']);
415     $this->drupalGet('<front>');
416     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
417
418     // Verify a cache hit, but also the presence of the correct cache tags.
419     $this->drupalGet('<front>');
420     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
421     $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
422     $cid = implode(':', $cid_parts);
423     $cache_entry = \Drupal::cache('page')->get($cid);
424     $expected_cache_tags = [
425       'config:block_list',
426       'block_view',
427       'config:block.block.powered',
428       'config:block.block.powered-2',
429       'config:user.role.anonymous',
430       'http_response',
431       'rendered',
432     ];
433     sort($expected_cache_tags);
434     $this->assertEqual($cache_entry->tags, $expected_cache_tags);
435     $expected_cache_tags = [
436       'block_view',
437       'config:block.block.powered',
438       'rendered',
439     ];
440     sort($expected_cache_tags);
441     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
442     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
443     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
444     $expected_cache_tags = [
445       'block_view',
446       'config:block.block.powered-2',
447       'rendered',
448     ];
449     sort($expected_cache_tags);
450     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
451     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
452     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
453
454     // Now we should have a cache hit again.
455     $this->drupalGet('<front>');
456     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
457
458     // Delete the "Powered by Drupal" blocks; verify a cache miss.
459     entity_delete_multiple('block', ['powered', 'powered-2']);
460     $this->drupalGet('<front>');
461     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
462   }
463
464   /**
465    * Tests that a link exists to block layout from the appearance form.
466    */
467   public function testThemeAdminLink() {
468     $this->drupalPlaceBlock('help_block', ['region' => 'help']);
469     $theme_admin = $this->drupalCreateUser([
470       'administer blocks',
471       'administer themes',
472       'access administration pages',
473     ]);
474     $this->drupalLogin($theme_admin);
475     $this->drupalGet('admin/appearance');
476     $this->assertText('You can place blocks for each theme on the block layout page');
477     $this->assertLinkByHref('admin/structure/block');
478   }
479
480   /**
481    * Tests that uninstalling a theme removes its block configuration.
482    */
483   public function testUninstallTheme() {
484     /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
485     $theme_handler = \Drupal::service('theme_handler');
486
487     $theme_handler->install(['seven']);
488     $this->config('system.theme')->set('default', 'seven')->save();
489     $block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']);
490     $this->drupalGet('<front>');
491     $this->assertText('Powered by Drupal');
492
493     $this->config('system.theme')->set('default', 'classy')->save();
494     $theme_handler->uninstall(['seven']);
495
496     // Ensure that the block configuration does not exist anymore.
497     $this->assertIdentical(NULL, Block::load($block->id()));
498   }
499
500   /**
501    * Tests the block access.
502    */
503   public function testBlockAccess() {
504     $this->drupalPlaceBlock('test_access', ['region' => 'help']);
505
506     $this->drupalGet('<front>');
507     $this->assertNoText('Hello test world');
508
509     \Drupal::state()->set('test_block_access', TRUE);
510     $this->drupalGet('<front>');
511     $this->assertText('Hello test world');
512   }
513
514   /**
515    * Tests block_user_role_delete.
516    */
517   public function testBlockUserRoleDelete() {
518     $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
519     $role1->save();
520
521     $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
522     $role2->save();
523
524     $block = Block::create([
525       'id' => $this->randomMachineName(),
526       'plugin' => 'system_powered_by_block',
527     ]);
528
529     $block->setVisibilityConfig('user_role', [
530       'roles' => [
531         $role1->id() => $role1->id(),
532         $role2->id() => $role2->id(),
533       ],
534     ]);
535
536     $block->save();
537
538     $this->assertEqual($block->getVisibility()['user_role']['roles'], [
539       $role1->id() => $role1->id(),
540       $role2->id() => $role2->id()
541     ]);
542
543     $role1->delete();
544
545     $block = Block::load($block->id());
546     $this->assertEqual($block->getVisibility()['user_role']['roles'], [
547       $role2->id() => $role2->id()
548     ]);
549   }
550
551 }