You are here

protected function FileUpload::prepareFilename in GraphQL 8.4

Prepares the filename to strip out any malicious extensions.

Parameters

string $filename: The file name.

array $validators: The array of upload validators.

Return value

string The prepared/munged filename.

1 call to FileUpload::prepareFilename()
FileUpload::saveFileUpload in src/GraphQL/Utility/FileUpload.php
Validates an uploaded file, saves it and returns a file upload response.

File

src/GraphQL/Utility/FileUpload.php, line 373

Class

FileUpload
Service to manage file uploads within GraphQL mutations.

Namespace

Drupal\graphql\GraphQL\Utility

Code

protected function prepareFilename(string $filename, array &$validators) : string {

  // Don't rename if 'allow_insecure_uploads' evaluates to TRUE.
  if (!$this->systemFileConfig
    ->get('allow_insecure_uploads')) {
    if (!empty($validators['file_validate_extensions'][0])) {

      // If there is a file_validate_extensions validator and a list of
      // valid extensions, munge the filename to protect against possible
      // malicious extension hiding within an unknown file type. For example,
      // "filename.html.foo".
      $filename = file_munge_filename($filename, $validators['file_validate_extensions'][0]);
    }

    // Rename potentially executable files, to help prevent exploits (i.e.
    // will rename filename.php.foo and filename.php to filename._php._foo.txt
    // and filename._php.txt, respectively).
    if (preg_match(FILE_INSECURE_EXTENSION_REGEX, $filename)) {

      // If the file will be rejected anyway due to a disallowed extension, it
      // should not be renamed; rather, we'll let file_validate_extensions()
      // reject it below.
      $passes_validation = FALSE;
      if (!empty($validators['file_validate_extensions'][0])) {

        /** @var \Drupal\file\FileInterface $file */
        $file = $this->fileStorage
          ->create([]);
        $file
          ->setFilename($filename);
        $passes_validation = empty(file_validate_extensions($file, $validators['file_validate_extensions'][0]));
      }
      if (empty($validators['file_validate_extensions'][0]) || $passes_validation) {
        if (substr($filename, -4) != '.txt') {

          // The destination filename will also later be used to create the
          // URI.
          $filename .= '.txt';
        }
        $filename = file_munge_filename($filename, $validators['file_validate_extensions'][0] ?? '');

        // The .txt extension may not be in the allowed list of extensions. We
        // have to add it here or else the file upload will fail.
        if (!empty($validators['file_validate_extensions'][0])) {
          $validators['file_validate_extensions'][0] .= ' txt';
        }
      }
    }
  }
  return $filename;
}