realpath example



    $this->drupalGet('node/add');
    $this->waitForEditor();
    $page->fillField('title[0][value]', 'My test content');

    // Ensure that CKEditor 5 is focused.     $this->click('.ck-content');

    $this->assertNotEmpty($image_upload_field = $page->find('css', '.ck-file-dialog-button input[type="file"]'));
    $image = $this->getTestFiles('image')[0];
    $image_upload_field->attachFile($this->container->get('file_system')->realpath($image->uri));
    $assert_session->waitForElementVisible('css', '.ck-widget.image');

    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '.ck-balloon-panel .ck-text-alternative-form'));
    $alt_override_input = $page->find('css', '.ck-balloon-panel .ck-text-alternative-form input[type=text]');
    $this->assertSame('', $alt_override_input->getValue());
    $alt_override_input->setValue('</em> Kittens & llamas are cute');
    $this->getBalloonButton('Save')->click();
    $page->pressButton('Save');

    $uploaded_image = File::load(1);
    $image_uuid = $uploaded_image->uuid();
    
// This request will have the default 'application/octet-stream' content     // type header.     $response = $this->fileRequest($uri$this->testFileData);

    $this->assertSame(201, $response->getStatusCode());

    // Simulate a race condition where two files are uploaded at almost the same     // time, by removing the first uploaded file from disk (leaving the entry in     // the file_managed table) before trying to upload another file with the     // same name.     unlink(\Drupal::service('file_system')->realpath('public://foobar/example.txt'));

    // Make the same request again. The upload should fail validation.     $response = $this->fileRequest($uri$this->testFileData);
    $this->assertResourceErrorResponse(422, PlainTextOutput::renderFromHtml("Unprocessable Entity: file validation failed.\nThe file public://foobar/example.txt already exists. Enter a unique file URI.")$uri$response);
  }

  /** * Tests using the file upload route with any path prefixes being stripped. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives */
  
$path = parent::getLocalPath($uri);
    if (!$path || str_starts_with($path, 'vfs://')) {
      return $path;
    }

    if (Settings::get('sa_core_2022_012_override') === TRUE) {
      return $path;
    }

    $private_path = Settings::get('file_private_path');
    if ($private_path) {
      $private_path = realpath($private_path);
      if ($private_path && str_starts_with($path$private_path)) {
        return FALSE;
      }
    }

    return $path;
  }

}
public function getPHPBinary(Request $request): string
    {
        $phpBinary = $request->getSession()->get('phpBinary');
        \assert(\is_string($phpBinary));

        return $phpBinary;
    }

    public function getProjectDir(): string
    {
        $fileName = realpath($_SERVER['SCRIPT_FILENAME']);
        \assert(\is_string($fileName));

        return \dirname($fileName);
    }

    public function getShopwareLocation(): string
    {
        $projectDir = $this->getProjectDir();

        $composerLookup = \dirname($projectDir) . '/composer.lock';

        
$file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$media_image->getAttribute('src'));
    $field = $assert_session->elementExists('xpath', '/div[1]', $media_item);
    $assert_session->elementExists('xpath', '/div[@class="visually-hidden"]', $field);
    $assert_session->elementNotExists('xpath', '//a', $field);

    $test_filename = $this->randomMachineName() . '.txt';
    $test_filepath = 'public://' . $test_filename;
    file_put_contents($test_filepath$this->randomMachineName());
    $this->drupalGet("media/add/document");
    $page->attachFileToField("files[field_media_document_0]", \Drupal::service('file_system')->realpath($test_filepath));
    $result = $assert_session->waitForButton('Remove');
    $this->assertNotEmpty($result);
    $page->pressButton('Save');

    // Go to the media entity view.     $this->drupalGet($this->assertLinkToCreatedMedia());

    // Check if the default media name is generated as expected.     $assert_session->elementTextContains('css', 'h1', $test_filename);
    // Here we expect to see only the linked filename.     // Assert only one element in the content region.

    protected function buildFilepath(Smarty_Template_Source $source, ?Smarty_Internal_Template $_template = null)
    {
        ++$this->index;
        $file = $source->name;
        $hit = false;

        foreach ($source->smarty->getTemplateDir() as $_directory) {
            $_filePath = Enlight_Loader::realpath($_directory . $file);
            if (\is_string($_filePath) && $this->fileExists($source$_filePath)) {
                if ($hit) {
                    return $_filePath;
                }
                if ($_template->parent->source->filepath == $_filePath) {
                    $hit = true;
                }
            }
        }

        return parent::buildFilepath($source$_template);
    }
public function testFilterDuplicateTransPaths()
    {
        $transPaths = [
            $this->translationDir.'/a/test/folder/with/a/subfolder',
            $this->translationDir.'/a/test/folder/',
            $this->translationDir.'/a/test/folder/with/a/subfolder/and/a/file.txt',
            $this->translationDir.'/a/different/test/folder',
        ];

        foreach ($transPaths as $transPath) {
            if (realpath($transPath)) {
                continue;
            }

            if (preg_match('/\.[a-z]+$/', $transPath)) {
                if (!realpath(\dirname($transPath))) {
                    mkdir(\dirname($transPath), 0777, true);
                }

                touch($transPath);
            } else {
                mkdir($transPath, 0777, true);
            }

abstract class SMime
{
    protected function normalizeFilePath(string $path): string
    {
        if (!file_exists($path)) {
            throw new RuntimeException(sprintf('File does not exist: "%s".', $path));
        }

        return 'file://'.str_replace('\\', '/', realpath($path));
    }

    protected function iteratorToFile(iterable $iterator$stream): void
    {
        foreach ($iterator as $chunk) {
            fwrite($stream$chunk);
        }
    }

    protected function convertMessageToSMimePart($stream, string $type, string $subtype): SMimePart
    {
        
new CheckCircularReferencesPass())->process($this->container);
        }

        $this->analyzeReferences();
        $this->docStar = $options['debug'] ? '*' : '';

        if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) {
            // Build a regexp where the first root dirs are mandatory,             // but every other sub-dir is optional up to the full path in $dir             // Mandate at least 1 root dir and not more than 5 optional dirs.
            $dir = explode(\DIRECTORY_SEPARATOR, realpath($dir));
            $i = \count($dir);

            if (2 + (int) ('\\' === \DIRECTORY_SEPARATOR) <= $i) {
                $regex = '';
                $lastOptionalDir = $i > 8 ? $i - 5 : (2 + (int) ('\\' === \DIRECTORY_SEPARATOR));
                $this->targetDirMaxMatches = $i - $lastOptionalDir;

                while (--$i >= $lastOptionalDir) {
                    $regex = sprintf('(%s%s)?', preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#')$regex);
                }

                
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooClassWithDefaultObjectAttribute;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooClassWithEnumAttribute;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooUnitEnum;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument;

class XmlDumperTest extends TestCase
{
    protected static string $fixturesPath;

    public static function setUpBeforeClass(): void
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    public function testDump()
    {
        $dumper = new XmlDumper(new ContainerBuilder());

        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services1.xml', $dumper->dump(), '->dump() dumps an empty container as an empty XML file');
    }

    public function testExportParameters()
    {
        
$targetPath = $targetDir.'/test.copy.gif';
        @unlink($path);
        @unlink($targetPath);
        copy(__DIR__.'/Fixtures/test.gif', $path);

        $file = new File($path);
        $movedFile = $file->move($targetDir);
        $this->assertInstanceOf(File::class$movedFile);

        $this->assertFileExists($targetPath);
        $this->assertFileDoesNotExist($path);
        $this->assertEquals(realpath($targetPath)$movedFile->getRealPath());

        @unlink($targetPath);
    }

    public function testMoveWithNewName()
    {
        $path = __DIR__.'/Fixtures/test.copy.gif';
        $targetDir = __DIR__.'/Fixtures/directory';
        $targetPath = $targetDir.'/test.newname.gif';
        @unlink($path);
        @unlink($targetPath);
        

    if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
        return true;
    }

    /* * This is definitive if true but fails if $path does not exist or contains * a symbolic link. */
    if ( realpath( $path ) === $path ) {
        return true;
    }

    if ( strlen( $path ) === 0 || '.' === $path[0] ) {
        return false;
    }

    // Windows allows absolute paths like this.     if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) {
        return true;
    }

    
$this->assertNotEquals($nid$node->getRevisionId(), 'Node revision exists.');
    }
    $this->drupalGet("node/$nid/edit");
    $page = $this->getSession()->getPage();

    // Attach files to the node.     $field_storage = FieldStorageConfig::loadByName('node', $field_name);
    // File input name depends on number of files already uploaded.     $field_num = count($node->{$field_name});
    foreach ($files as $i => $file) {
      $delta = $field_num + $i;
      $file_path = $this->container->get('file_system')->realpath($file->getFileUri());
      $name = 'files[' . $field_name . '_' . $delta . ']';
      if ($field_storage->getCardinality() != 1) {
        $name .= '[]';
      }
      if (count($files) == 1) {
        $edit[$name] = $file_path;
      }
      else {
        $page->attachFileToField($name$file_path);
        $this->submitForm([], 'Upload');
      }
    }
    // confirm that only the session that uploaded it may view it.     $this->drupalLogout();
    user_role_change_permissions(
      RoleInterface::ANONYMOUS_ID,
      [
        "create $type_name content" => TRUE,
        'access content' => TRUE,
      ]
    );
    $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.

  public function testAJAXValidationMessage() {
    $field_name = strtolower($this->randomMachineName());
    $this->createImageField($field_name, 'article', ['cardinality' => -1]);

    $this->drupalGet('node/add/article');
    /** @var \Drupal\file\FileInterface[] $text_files */
    $text_files = $this->drupalGetTestFiles('text');
    $text_file = reset($text_files);

    $field = $this->getSession()->getPage()->findField('files[' . $field_name . '_0][]');
    $field->attachFile($this->container->get('file_system')->realpath($text_file->uri));
    $this->assertSession()->waitForElement('css', '.messages--error');

    // Verify that Ajax validation messages are displayed only once.     $this->assertSession()->elementsCount('xpath', '//div[contains(@class, "messages--error")]', 1);
  }

  /** * Tests that image field validation works with other form submit handlers. */
  public function testFriendlyAjaxValidation() {
    // Add a custom field to the Article content type that contains an AJAX
Home | Imprint | This part of the site doesn't use cookies.