isTemporary example

        if (!empty($input['fids'])) {
          $fids = [];
          foreach ($input['fids'] as $fid) {
            if ($file = File::load($fid)) {
              $fids[] = $file->id();
              if (!$file->access('download')) {
                $force_default = TRUE;
                break;
              }
              // Temporary files that belong to other users should never be               // allowed.               if ($file->isTemporary()) {
                if ($file->getOwnerId() != \Drupal::currentUser()->id()) {
                  $force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,                 // they are not allowed to reuse temporary files at all. But                 // they do need to be able to reuse their own files from earlier                 // submissions of the same form, so to allow that, check for the                 // token added by $this->processManagedFile().                 elseif (\Drupal::currentUser()->isAnonymous()) {
                  $token = NestedArray::getValue($form_state->getUserInput()array_merge($element['#parents']['file_' . $file->id(), 'fid_token']));
                  
    $assert_session->elementNotExists('css', '.js-media-library-add-form[data-input]');
    $this->addMediaFileToField('Add files', $this->container->get('file_system')->realpath($png_image->uri));
    $this->assertMediaAdded();
    $assert_session->elementExists('css', '.js-media-library-add-form[data-input]');
    // We do not have pre-selected items, so the container should not be added     // to the form.     $assert_session->pageTextNotContains('Additional selected media');
    // Files are temporary until the form is saved.     $files = $file_storage->loadMultiple();
    $file = array_pop($files);
    $this->assertSame('public://type-three-dir', $file_system->dirname($file->getFileUri()));
    $this->assertTrue($file->isTemporary());
    // Assert the revision_log_message field is not shown.     $upload_form = $assert_session->elementExists('css', '.js-media-library-add-form');
    $assert_session->fieldNotExists('Revision log message', $upload_form);
    // Assert the name field contains the filename and the alt text is required.     $assert_session->fieldValueEquals('Name', $png_image->filename);
    $this->pressSaveButton(TRUE);
    $this->waitForText('Alternative text field is required');
    $page->fillField('Alternative text', $this->randomString());
    $this->pressSaveButton();
    $this->assertJsCondition('jQuery("input[name=\'media_library_select_form[0]\']").is(":focus")');
    // The file should be permanent now.


  /** * {@inheritdoc} */
  public function testPost() {
    $file_storage = $this->container->get('entity_type.manager')->getStorage('file');

    // Step 1: upload file, results in File entity marked temporary.     $this->uploadFile();
    $file = $file_storage->loadUnchanged(3);
    $this->assertTrue($file->isTemporary());
    $this->assertFalse($file->isPermanent());

    // Step 2: create Media entity using the File, makes File entity permanent.     parent::testPost();
    $file = $file_storage->loadUnchanged(3);
    $this->assertFalse($file->isTemporary());
    $this->assertTrue($file->isPermanent());
  }

  /** * Tests the 'file_upload' REST resource plugin. * * This test duplicates some of the 'file_upload' REST resource plugin test * coverage. * * @see \Drupal\Tests\rest\Functional\FileUploadResourceTestBase */
\Drupal::entityTypeManager()->getStorage('file')->resetCache();

    // Ensure the first and replaced second files are untouched.     $file = File::load($first_fid);
    $this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');

    $file = File::load($replaced_second_fid);
    $this->assertTrue($file->isPermanent());

    // Ensure the file status of the third file is now temporary.     $file = File::load($third_fid);
    $this->assertTrue($file->isTemporary());

    // Delete the all translations.     $this->drupalGet('node/' . $default_language_node->id() . '/delete');
    $this->submitForm([], 'Delete all translations');

    \Drupal::entityTypeManager()->getStorage('file')->resetCache();

    // Ensure the file status of the all files are now temporary.     $file = File::load($first_fid);
    $this->assertTrue($file->isTemporary(), 'First file still exists and is temporary.');

    
    $this->assertSame($this->testFileData, file_get_contents('public://foobar/example.txt'));

    // Test the file again but using 'filename' in the Content-Disposition     // header with no 'file' prefix.     $response = $this->fileRequest($uri$this->testFileData, ['Content-Disposition' => 'filename="example.txt"']);
    $this->assertSame(201, $response->getStatusCode());
    $expected = $this->getExpectedNormalizedEntity(2, 'example_0.txt');
    $this->assertResponseData($expected$response);

    // Check the actual file data.     $this->assertSame($this->testFileData, file_get_contents('public://foobar/example_0.txt'));
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('rest.entity.entity_test.POST')
      ->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions('POST'));

    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    
// Clear out the call to hook_file_load().     file_test_reset();

    $file_usage->delete($file, 'testing', 'test', 1);
    $usage = $file_usage->listUsage($file);
    $this->assertFileHooksCalled(['load', 'update']);
    $this->assertEmpty($usage, 'File usage data was removed.');
    $this->assertFileExists($file->getFileUri());
    $file = File::load($file->id());
    $this->assertNotEmpty($file, 'File still exists in the database.');
    $this->assertTrue($file->isTemporary(), 'File is temporary.');
    file_test_reset();

    // Call file_cron() to clean up the file. Make sure the changed timestamp     // of the file is older than the system.file.temporary_maximum_age     // configuration value. We use an UPDATE statement because using the API     // would set the timestamp.     Database::getConnection()->update('file_managed')
      ->fields([
        'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1),
      ])
      ->condition('fid', $file->id())
      
$type_name = 'article';
    $field_name = 'test_file_field';
    $this->createFileField($field_name, 'node', $type_name);

    $test_file = $this->getTestFile('text');
    $type = 'no-js';
    // Create a temporary file owned by the victim user. This will be as if     // they had uploaded the file, but not saved the node they were editing     // or creating.     $victim_tmp_file = $this->createTemporaryFile('some text', $victim_user);
    $victim_tmp_file = File::load($victim_tmp_file->id());
    $this->assertTrue($victim_tmp_file->isTemporary(), 'New file saved to disk is temporary.');
    $this->assertNotEmpty($victim_tmp_file->id(), 'New file has an fid.');
    $this->assertEquals($victim_user->id()$victim_tmp_file->getOwnerId(), 'New file belongs to the victim.');

    // Have attacker create a new node with a different uploaded file and     // ensure it got uploaded successfully.     $edit = [
      'title[0][value]' => $type . '-title',
    ];

    // Attach a file to a node.     $edit['files[' . $field_name . '_0]'] = $this->container->get('file_system')->realpath($test_file->getFileUri());
    
\Drupal::entityTypeManager()->getStorage('file')->resetCache();

    // Ensure the first and replaced second files are untouched.     $file = File::load($first_fid);
    $this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');

    $file = File::load($replaced_second_fid);
    $this->assertTrue($file->isPermanent());

    // Ensure the file status of the third file is now temporary.     $file = File::load($third_fid);
    $this->assertTrue($file->isTemporary());

    // Delete the all translations.     $this->drupalGet('node/' . $default_language_node->id() . '/delete');
    $this->submitForm([], 'Delete all translations');

    \Drupal::entityTypeManager()->getStorage('file')->resetCache();

    // Ensure the file status of the all files are now temporary.     $file = File::load($first_fid);
    $this->assertTrue($file->isTemporary(), 'First file still exists and is temporary.');

    
    $this->assertSame($this->testFileData, file_get_contents('public://foobar/example.txt'));

    // Test the file again but using 'filename' in the Content-Disposition     // header with no 'file' prefix.     $response = $this->fileRequest($uri$this->testFileData, ['Content-Disposition' => 'filename="example.txt"']);
    $this->assertSame(201, $response->getStatusCode());
    $expected = $this->getExpectedDocument(2, 'example_0.txt');
    $this->assertResponseData($expected$response);

    // Check the actual file data.     $this->assertSame($this->testFileData, file_get_contents('public://foobar/example_0.txt'));
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('jsonapi.entity_test--entity_test.collection.post');
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument());
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    

    );
    $test_file = $this->getTestFile('text');
    $this->drupalGet('node/add/' . $type_name);
    $edit = ['files[' . $field_name . '_0]' => $file_system->realpath($test_file->getFileUri())];
    $this->submitForm($edit, 'Upload');
    /** @var \Drupal\file\FileStorageInterface $file_storage */
    $file_storage = $this->container->get('entity_type.manager')->getStorage('file');
    $files = $file_storage->loadByProperties(['uid' => 0]);
    $this->assertCount(1, $files, 'Loaded one anonymous file.');
    $file = end($files);
    $this->assertTrue($file->isTemporary(), 'File is temporary.');
    $usage = $this->container->get('file.usage')->listUsage($file);
    $this->assertEmpty($usage, 'No file usage found.');
    $file_url = $file->createFileUrl(FALSE);
    // Ensure the anonymous uploader has access to the temporary file.     $this->drupalGet($file_url);
    $this->assertSession()->statusCodeEquals(200);
    // Close the prior connection and remove the session cookie.     $this->getSession()->reset();
    // Ensure that a different anonymous user cannot access the temporary file.     $this->drupalGet($file_url);
    $this->assertSession()->statusCodeEquals(403);

    
$this->assertEquals(2, $usage[2]->count, 'Correct count');
  }

  /** * Tests file usage deletion when files are made temporary. */
  public function testRemoveUsageTemporary() {
    $this->config('file.settings')
      ->set('make_unused_managed_files_temporary', TRUE)
      ->save();
    $file = $this->doTestRemoveUsage();
    $this->assertTrue($file->isTemporary());
  }

  /** * Tests file usage deletion when files are made temporary. */
  public function testRemoveUsageNonTemporary() {
    $this->config('file.settings')
      ->set('make_unused_managed_files_temporary', FALSE)
      ->save();
    $file = $this->doTestRemoveUsage();
    $this->assertFalse($file->isTemporary());
  }
Home | Imprint | This part of the site doesn't use cookies.