Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / file / tests / src / Kernel / UsageTest.php
1 <?php
2
3 namespace Drupal\Tests\file\Kernel;
4
5 use Drupal\field\Entity\FieldConfig;
6 use Drupal\field\Entity\FieldStorageConfig;
7 use Drupal\language\Entity\ConfigurableLanguage;
8 use Drupal\language\Entity\ContentLanguageSettings;
9 use Drupal\node\Entity\Node;
10 use Drupal\node\Entity\NodeType;
11
12 /**
13  * Tests file usage functions.
14  *
15  * @group file
16  */
17 class UsageTest extends FileManagedUnitTestBase {
18   /**
19    * Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::listUsage().
20    */
21   public function testGetUsage() {
22     $file = $this->createFile();
23     db_insert('file_usage')
24       ->fields([
25         'fid' => $file->id(),
26         'module' => 'testing',
27         'type' => 'foo',
28         'id' => 1,
29         'count' => 1
30       ])
31       ->execute();
32     db_insert('file_usage')
33       ->fields([
34         'fid' => $file->id(),
35         'module' => 'testing',
36         'type' => 'bar',
37         'id' => 2,
38         'count' => 2
39       ])
40       ->execute();
41
42     $usage = $this->container->get('file.usage')->listUsage($file);
43
44     $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
45     $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
46     $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
47     $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
48     $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
49   }
50
51   /**
52    * Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::add().
53    */
54   public function testAddUsage() {
55     $file = $this->createFile();
56     $file_usage = $this->container->get('file.usage');
57     $file_usage->add($file, 'testing', 'foo', 1);
58     // Add the file twice to ensure that the count is incremented rather than
59     // creating additional records.
60     $file_usage->add($file, 'testing', 'bar', 2);
61     $file_usage->add($file, 'testing', 'bar', 2);
62
63     $usage = db_select('file_usage', 'f')
64       ->fields('f')
65       ->condition('f.fid', $file->id())
66       ->execute()
67       ->fetchAllAssoc('id');
68     $this->assertEqual(count($usage), 2, 'Created two records');
69     $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
70     $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
71     $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
72     $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
73     $this->assertEqual($usage[1]->count, 1, 'Correct count');
74     $this->assertEqual($usage[2]->count, 2, 'Correct count');
75   }
76
77   /**
78    * Tests file usage deletion when files are made temporary.
79    */
80   public function testRemoveUsageTemporary() {
81     $this->config('file.settings')
82       ->set('make_unused_managed_files_temporary', TRUE)
83       ->save();
84     $file = $this->doTestRemoveUsage();
85     $this->assertTrue($file->isTemporary());
86   }
87
88   /**
89    * Tests file usage deletion when files are made temporary.
90    */
91   public function testRemoveUsageNonTemporary() {
92     $this->config('file.settings')
93       ->set('make_unused_managed_files_temporary', FALSE)
94       ->save();
95     $file = $this->doTestRemoveUsage();
96     $this->assertFalse($file->isTemporary());
97   }
98
99   /**
100    * Tests \Drupal\file\FileUsage\DatabaseFileUsageBackend::delete().
101    */
102   public function doTestRemoveUsage() {
103     $file = $this->createFile();
104     $file->setPermanent();
105     $file_usage = $this->container->get('file.usage');
106     db_insert('file_usage')
107       ->fields([
108         'fid' => $file->id(),
109         'module' => 'testing',
110         'type' => 'bar',
111         'id' => 2,
112         'count' => 3,
113       ])
114       ->execute();
115
116     // Normal decrement.
117     $file_usage->delete($file, 'testing', 'bar', 2);
118     $count = db_select('file_usage', 'f')
119       ->fields('f', ['count'])
120       ->condition('f.fid', $file->id())
121       ->execute()
122       ->fetchField();
123     $this->assertEqual(2, $count, 'The count was decremented correctly.');
124
125     // Multiple decrement and removal.
126     $file_usage->delete($file, 'testing', 'bar', 2, 2);
127     $count = db_select('file_usage', 'f')
128       ->fields('f', ['count'])
129       ->condition('f.fid', $file->id())
130       ->execute()
131       ->fetchField();
132     $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
133
134     // Non-existent decrement.
135     $file_usage->delete($file, 'testing', 'bar', 2);
136     $count = db_select('file_usage', 'f')
137       ->fields('f', ['count'])
138       ->condition('f.fid', $file->id())
139       ->execute()
140       ->fetchField();
141     $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
142     return $file;
143   }
144
145   /**
146    * Create files for all the possible combinations of age and status.
147    *
148    * We are using UPDATE statements because using the API would set the
149    * timestamp.
150    */
151   public function createTempFiles() {
152     // Temporary file that is old.
153     $temp_old = file_save_data('');
154     db_update('file_managed')
155       ->fields([
156         'status' => 0,
157         'changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1,
158       ])
159       ->condition('fid', $temp_old->id())
160       ->execute();
161     $this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was created correctly.');
162
163     // Temporary file that is new.
164     $temp_new = file_save_data('');
165     db_update('file_managed')
166       ->fields(['status' => 0])
167       ->condition('fid', $temp_new->id())
168       ->execute();
169     $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was created correctly.');
170
171     // Permanent file that is old.
172     $perm_old = file_save_data('');
173     db_update('file_managed')
174       ->fields(['changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1])
175       ->condition('fid', $temp_old->id())
176       ->execute();
177     $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was created correctly.');
178
179     // Permanent file that is new.
180     $perm_new = file_save_data('');
181     $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was created correctly.');
182     return [$temp_old, $temp_new, $perm_old, $perm_new];
183   }
184
185   /**
186    * Ensure that temporary files are removed by default.
187    */
188   public function testTempFileCleanupDefault() {
189     list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
190
191     // Run cron and then ensure that only the old, temp file was deleted.
192     $this->container->get('cron')->run();
193     $this->assertFalse(file_exists($temp_old->getFileUri()), 'Old temp file was correctly removed.');
194     $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
195     $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
196     $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
197   }
198
199   /**
200    * Ensure that temporary files are kept as configured.
201    */
202   public function testTempFileNoCleanup() {
203     list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
204
205     // Set the max age to 0, meaning no temporary files will be deleted.
206     $this->config('system.file')
207       ->set('temporary_maximum_age', 0)
208       ->save();
209
210     // Run cron and then ensure that no file was deleted.
211     $this->container->get('cron')->run();
212     $this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was correctly ignored.');
213     $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
214     $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
215     $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
216   }
217
218   /**
219    * Ensure that temporary files are kept as configured.
220    */
221   public function testTempFileCustomCleanup() {
222     list($temp_old, $temp_new, $perm_old, $perm_new) = $this->createTempFiles();
223
224     // Set the max age to older than default.
225     $this->config('system.file')
226       ->set('temporary_maximum_age', 21600 + 2)
227       ->save();
228
229     // Run cron and then ensure that more files were deleted.
230     $this->container->get('cron')->run();
231     $this->assertTrue(file_exists($temp_old->getFileUri()), 'Old temp file was correctly ignored.');
232     $this->assertTrue(file_exists($temp_new->getFileUri()), 'New temp file was correctly ignored.');
233     $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was correctly ignored.');
234     $this->assertTrue(file_exists($perm_new->getFileUri()), 'New permanent file was correctly ignored.');
235   }
236
237   /**
238    * Tests file usage with translated entities.
239    */
240   public function testFileUsageWithEntityTranslation() {
241     /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
242     $file_usage = $this->container->get('file.usage');
243
244     $this->enableModules(['node', 'language']);
245     $this->installEntitySchema('node');
246     $this->installSchema('node', ['node_access']);
247
248     // Activate English and Romanian languages.
249     ConfigurableLanguage::create(['id' => 'en'])->save();
250     ConfigurableLanguage::create(['id' => 'ro'])->save();
251
252     NodeType::create(['type' => 'page'])->save();
253     ContentLanguageSettings::loadByEntityTypeBundle('node', 'page')
254       ->setLanguageAlterable(FALSE)
255       ->setDefaultLangcode('en')
256       ->save();
257     // Create a file field attached to 'page' node-type.
258     FieldStorageConfig::create([
259       'type' => 'file',
260       'entity_type' => 'node',
261       'field_name' => 'file',
262     ])->save();
263     FieldConfig::create([
264       'entity_type' => 'node',
265       'bundle' => 'page',
266       'field_name' => 'file',
267       'label' => 'File',
268     ])->save();
269
270     // Create a node, attach a file and add a Romanian translation.
271     $node = Node::create(['type' => 'page', 'title' => 'Page']);
272     $node
273       ->set('file', $file = $this->createFile())
274       ->addTranslation('ro', $node->getTranslation('en')->toArray())
275       ->save();
276
277     // Check that the file is used twice.
278     $usage = $file_usage->listUsage($file);
279     $this->assertEquals(2, $usage['file']['node'][$node->id()]);
280
281     // Remove the Romanian translation.
282     $node->removeTranslation('ro');
283     $node->save();
284
285     // Check that one usage has been removed and is used only once now.
286     $usage = $file_usage->listUsage($file);
287     $this->assertEquals(1, $usage['file']['node'][$node->id()]);
288   }
289
290 }