You are here

protected function TemporaryJsonapiFileFieldUploader::prepareFilename in JSON:API 8.2

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 TemporaryJsonapiFileFieldUploader::prepareFilename()
TemporaryJsonapiFileFieldUploader::handleFileUploadForField in src/Controller/TemporaryJsonapiFileFieldUploader.php
Creates and validates a file entity for a file field from a file stream.

File

src/Controller/TemporaryJsonapiFileFieldUploader.php, line 400

Class

TemporaryJsonapiFileFieldUploader
Reads data from an upload stream and creates a corresponding file entity.

Namespace

Drupal\jsonapi\Controller

Code

protected function prepareFilename($filename, array &$validators) {
  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). Don't rename if 'allow_insecure_uploads'
  // evaluates to TRUE.
  if (!$this->systemFileConfig
    ->get('allow_insecure_uploads') && preg_match(FILE_INSECURE_EXTENSION_REGEX, $filename) && substr($filename, -4) != '.txt') {

    // The destination filename will also later be used to create the URI.
    $filename .= '.txt';

    // 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;
}