<?php

/**
 * @file
 * API for handling file uploads and server file management.
 */

use Drupal\Core\File\Exception\InvalidStreamWrapperException;
use Drupal\Core\File\FileSystemInterface;

/**
 * @defgroup file File interface
 * @{
 * Common file handling functions.
 */

/**
 * Indicates that the file is permanent and should not be deleted.
 *
 * Temporary files older than the system.file.temporary_maximum_age
 * configuration value will be, if clean-up not disabled, removed during cron
 * runs, but permanent files will not be removed during the file garbage
 * collection process.
 *
 * @deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use
 *   \Drupal\file\FileInterface::STATUS_PERMANENT or
 *   \Drupal\file\FileInterface::setPermanent() instead.
 *
 * @see https://www.drupal.org/node/3022147
 */
const FILE_STATUS_PERMANENT = 1;

/**
 * Creates a web-accessible URL for a stream to an external or local file.
 *
 * Compatibility: normal paths and stream wrappers.
 *
 * There are two kinds of local files:
 * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
 *   These are files that have either been uploaded by users or were generated
 *   automatically (for example through CSS aggregation).
 * - "shipped files", i.e. those outside of the files directory, which ship as
 *   part of Drupal core or contributed modules or themes.
 *
 * @param string $uri
 *   The URI to a file for which we need an external URL, or the path to a
 *   shipped file.
 *
 * @return string
 *   A string containing a URL that may be used to access the file.
 *   If the provided string already contains a preceding 'http', 'https', or
 *   '/', nothing is done and the same string is returned. If a stream wrapper
 *   could not be found to generate an external URL, then FALSE is returned.
 *
 * @deprecated in drupal:9.3.0 and is removed from drupal:10.0.0.
 *   Use the appropriate method on \Drupal\Core\File\FileUrlGeneratorInterface
 *   instead.
 *
 * @see https://www.drupal.org/node/2940031
 * @see https://www.drupal.org/node/515192
 * @see \Drupal\Core\File\FileUrlGeneratorInterface::generate()
 * @see \Drupal\Core\File\FileUrlGeneratorInterface::generateString()
 * @see \Drupal\Core\File\FileUrlGeneratorInterface::generateAbsoluteString()
 * @see \Drupal\Core\File\FileUrlGeneratorInterface::transformRelative()
 */
function file_create_url($uri) {
  @trigger_error('file_create_url() is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use the appropriate method on \Drupal\Core\File\FileUrlGeneratorInterface instead. See https://www.drupal.org/node/2940031', E_USER_DEPRECATED);
  if (is_null($uri)) {
    return NULL;
  }
  try {
    return \Drupal::service('file_url_generator')->generateAbsoluteString($uri);
  }
  catch (InvalidStreamWrapperException $e) {
    return FALSE;
  }
}

/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by
 *   FileUrlGeneratorInterface::generateString().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @deprecated in drupal:9.3.0 and is removed from drupal:10.0.0.
 *   Use \Drupal\Core\File\FileUrlGenerator::transformRelative() instead.
 *
 * @see https://www.drupal.org/node/2940031
 * @see \Drupal\Core\File\FileUrlGeneratorInterface::transformRelative()
 */
function file_url_transform_relative($file_url) {
  @trigger_error('file_url_transform_relative() is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use \Drupal\Core\File\FileUrlGenerator::transformRelative() instead. See https://www.drupal.org/node/2940031', E_USER_DEPRECATED);
  return \Drupal::service('file_url_generator')->transformRelative($file_url);
}

/**
 * Constructs a URI to Drupal's default files location given a relative path.
 *
 * @deprecated in drupal:9.3.0 and is removed from drupal:10.0.0 without
 *   replacement.
 *
 * @see https://www.drupal.org/node/3223091
 */
function file_build_uri($path) {
  @trigger_error('file_build_uri() is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0 without replacement. See https://www.drupal.org/node/3223091', E_USER_DEPRECATED);
  $uri = \Drupal::config('system.file')->get('default_scheme') . '://' . $path;
  /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
  $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
  return $stream_wrapper_manager->normalizeUri($uri);
}

/**
 * Modifies a filename as needed for security purposes.
 *
 * Munging a file name prevents unknown file extensions from masking exploit
 * files. When web servers such as Apache decide how to process a URL request,
 * they use the file extension. If the extension is not recognized, Apache
 * skips that extension and uses the previous file extension. For example, if
 * the file being requested is exploit.php.pps, and Apache does not recognize
 * the '.pps' extension, it treats the file as PHP and executes it. To make
 * this file name safe for Apache and prevent it from executing as PHP, the
 * .php extension is "munged" into .php_, making the safe file name
 * exploit.php_.pps.
 *
 * Specifically, this function adds an underscore to all extensions that are
 * between 2 and 5 characters in length, internal to the file name, and either
 * included in the list of unsafe extensions, or not included in $extensions.
 *
 * Function behavior is also controlled by the configuration
 * 'system.file:allow_insecure_uploads'. If it evaluates to TRUE, no alterations
 * will be made, if it evaluates to FALSE, the filename is 'munged'. *
 * @param $filename
 *   File name to modify.
 * @param $extensions
 *   A space-separated list of extensions that should not be altered. Note that
 *   extensions that are unsafe will be altered regardless of this parameter.
 * @param $alerts
 *   If TRUE, \Drupal::messenger()->addStatus() will be called to display
 *   a message if the file name was changed.
 *
 * @return string
 *   The potentially modified $filename.
 *
 * @deprecated in drupal:9.2.0 and is removed from drupal:10.0.0. Dispatch a
 *   \Drupal\Core\File\Event\FileUploadSanitizeNameEvent event instead.
 *
 * @see https://www.drupal.org/node/3032541
 */
function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  @trigger_error('file_munge_filename() is deprecated in drupal:9.2.0 and is removed from drupal:10.0.0. Dispatch a \Drupal\Core\File\Event\FileUploadSanitizeNameEvent event instead. See https://www.drupal.org/node/3032541', E_USER_DEPRECATED);
  $original = $filename;

  // Allow potentially insecure uploads for very savvy users and admin
  if (!\Drupal::config('system.file')->get('allow_insecure_uploads')) {
    // Remove any null bytes. See
    // http://php.net/manual/security.filesystem.nullbytes.php
    $filename = str_replace(chr(0), '', $filename);

    $allowed_extensions = array_unique(explode(' ', strtolower(trim($extensions))));

    // Remove unsafe extensions from the allowed list of extensions.
    $allowed_extensions = array_diff($allowed_extensions, FileSystemInterface::INSECURE_EXTENSIONS);

    // Split the filename up by periods. The first part becomes the basename
    // the last part the final extension.
    $filename_parts = explode('.', $filename);
    // Remove file basename.
    $new_filename = array_shift($filename_parts);
    // Remove final extension.
    $final_extension = array_pop($filename_parts);

    // Loop through the middle parts of the name and add an underscore to the
    // end of each section that could be a file extension but isn't in the list
    // of allowed extensions.
    foreach ($filename_parts as $filename_part) {
      $new_filename .= '.' . $filename_part;
      if (!in_array(strtolower($filename_part), $allowed_extensions) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
        $new_filename .= '_';
      }
    }
    $filename = $new_filename . '.' . $final_extension;

    if ($alerts && $original != $filename) {
      \Drupal::messenger()->addStatus(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $filename]));
    }
  }

  return $filename;
}

/**
 * Undoes the effect of file_munge_filename().
 *
 * @param $filename
 *   String with the filename to be unmunged.
 *
 * @return string
 *   An unmunged filename string.
 *
 * @deprecated in drupal:9.2.0 and is removed from drupal:10.0.0. Use
 *   str_replace() instead.
 *
 * @see https://www.drupal.org/node/3032541
 */
function file_unmunge_filename($filename) {
  @trigger_error('file_unmunge_filename() is deprecated in drupal:9.2.0 and is removed from drupal:10.0.0. Use str_replace() instead. See https://www.drupal.org/node/3032541', E_USER_DEPRECATED);
  return str_replace('_.', '.', $filename);
}

/**
 * @} End of "defgroup file".
 */
