From 97a6869145df2cb6df329217bb50be34c2109730 Mon Sep 17 00:00:00 2001
From: Alex Pott <alex.a.pott@googlemail.com>
Date: Thu, 7 Mar 2019 09:12:01 +0000
Subject: [PATCH] Issue #3021450 by kim.pepper, jibran, voleger, alexpott,
 Berdir: Add @trigger_error to deprecated functions in file.inc and replace
 their usages

---
 core/includes/file.inc                        | 32 ++++++++------
 core/includes/install.core.inc                |  6 ++-
 core/includes/install.inc                     |  2 +-
 core/lib/Drupal/Core/Config/FileStorage.php   |  4 +-
 .../Database/Driver/sqlite/Connection.php     |  2 +-
 .../Database/Driver/sqlite/Install/Tasks.php  |  2 +-
 .../MimeType/ExtensionMimeTypeGuesser.php     |  2 +-
 .../Drupal/Core/FileTransfer/FileTransfer.php |  4 +-
 core/lib/Drupal/Core/FileTransfer/Local.php   |  6 ++-
 core/lib/Drupal/Core/Image/Image.php          | 16 +++----
 .../Drupal/Core/StreamWrapper/LocalStream.php | 22 ++++++----
 .../StreamWrapper/StreamWrapperInterface.php  |  8 ++--
 core/lib/Drupal/Core/Updater/Updater.php      |  4 +-
 core/modules/color/color.module               | 24 +++++++----
 .../tests/src/Kernel/EditorFileUsageTest.php  |  2 +-
 core/modules/file/file.module                 | 10 ++---
 core/modules/file/src/Entity/File.php         |  2 +-
 .../src/Functional/FileTokenReplaceTest.php   |  2 +-
 .../src/Functional/SaveUploadFormTest.php     |  4 +-
 .../tests/src/Functional/SaveUploadTest.php   |  8 ++--
 .../file/tests/src/Kernel/SaveDataTest.php    |  4 +-
 .../file/tests/src/Kernel/ValidatorTest.php   |  6 ++-
 core/modules/image/src/Entity/ImageStyle.php  |  2 +-
 .../src/Plugin/Field/FieldType/ImageItem.php  |  6 +--
 .../Functional/ImageStylesPathAndUrlTest.php  |  2 +-
 .../LanguageUILanguageNegotiationTest.php     |  2 +-
 core/modules/locale/locale.bulk.inc           |  2 +-
 core/modules/locale/locale.install            |  2 +-
 core/modules/locale/locale.translation.inc    |  2 +-
 .../Tests/SimpleTestErrorCollectorTest.php    |  2 +-
 .../src/Plugin/ImageToolkit/GDToolkit.php     |  2 +-
 core/modules/system/system.module             | 10 +++--
 .../Functional/System/RetrieveFileTest.php    |  6 ++-
 core/modules/update/update.manager.inc        |  4 +-
 core/modules/update/update.module             | 10 ++++-
 .../KernelTests/Core/File/DirectoryTest.php   | 10 +++--
 .../KernelTests/Core/File/FileCopyTest.php    |  4 +-
 .../Core/File/FileSaveDataTest.php            |  2 +-
 .../Core/File/FileSystemDeprecationTest.php   | 42 +++++++++++++++++++
 .../KernelTests/Core/File/FileTestBase.php    |  2 +-
 .../Core/File/ReadOnlyStreamWrapperTest.php   | 10 +++--
 .../Core/File/UrlRewritingTest.php            | 10 +++--
 .../Drupal/Tests/Core/Image/ImageTest.php     | 33 ++++++++++++---
 43 files changed, 222 insertions(+), 115 deletions(-)

diff --git a/core/includes/file.inc b/core/includes/file.inc
index 104a31ff5405..ded0f8c89107 100644
--- a/core/includes/file.inc
+++ b/core/includes/file.inc
@@ -18,21 +18,23 @@
 use Drupal\Core\StreamWrapper\PublicStream;
 
 /**
- * Default mode for new directories. See drupal_chmod().
+ * Default mode for new directories.
  *
  * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::CHMOD_DIRECTORY.
  *
+ * @see \Drupal\Core\File\FileSystemInterface::chmod()
  * @see https://www.drupal.org/node/2418133
  */
 const FILE_CHMOD_DIRECTORY = FileSystem::CHMOD_DIRECTORY;
 
 /**
- * Default mode for new files. See drupal_chmod().
+ * Default mode for new files.
  *
  * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::CHMOD_FILE.
  *
+ * @see \Drupal\Core\File\FileSystemInterface::chmod()
  * @see https://www.drupal.org/node/2418133
  */
 const FILE_CHMOD_FILE = FileSystem::CHMOD_FILE;
@@ -372,7 +374,7 @@ function file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALS
 
   // Write the .htaccess file.
   if (file_exists($directory) && is_writable($directory) && file_put_contents($htaccess_path, $htaccess_lines)) {
-    return drupal_chmod($htaccess_path, 0444);
+    return \Drupal::service('file_system')->chmod($htaccess_path, 0444);
   }
   else {
     $variables = ['%directory' => $directory, '@htaccess' => $htaccess_lines];
@@ -527,17 +529,17 @@ function file_unmanaged_prepare($source, &$destination = NULL, $replace = FILE_E
 
   // Build a destination URI if necessary.
   if (!isset($destination)) {
-    $destination = file_build_uri(drupal_basename($source));
+    $destination = file_build_uri($file_system->basename($source));
   }
 
   // Prepare the destination directory.
   if (file_prepare_directory($destination)) {
     // The destination is already a directory, so append the source basename.
-    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
+    $destination = file_stream_wrapper_uri_normalize($destination . '/' . $file_system->basename($source));
   }
   else {
     // Perhaps $destination is a dir/file?
-    $dirname = drupal_dirname($destination);
+    $dirname = $file_system->dirname($destination);
     if (!file_prepare_directory($dirname)) {
       // The destination is not valid.
       $logger->notice('File %file could not be moved/copied because the destination directory %destination is not configured correctly.', ['%file' => $original_source, '%destination' => $dirname]);
@@ -1060,12 +1062,13 @@ function file_upload_max_size() {
 /**
  * Sets the permissions on a file or directory.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::chmod().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_chmod($uri, $mode = NULL) {
+  @trigger_error('drupal_chmod() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::chmod(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->chmod($uri, $mode);
 }
 
@@ -1096,24 +1099,26 @@ function drupal_realpath($uri) {
 /**
  * Gets the name of the directory from a given path.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::dirname().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_dirname($uri) {
+  @trigger_error('drupal_dirname() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::dirname(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->dirname($uri);
 }
 
 /**
  * Gets the filename from a given path.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::basename().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_basename($uri, $suffix = NULL) {
+  @trigger_error('drupal_basename() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::basename(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->basename($uri, $suffix);
 }
 
@@ -1121,36 +1126,39 @@ function drupal_basename($uri, $suffix = NULL) {
  * Creates a directory, optionally creating missing components in the path to
  * the directory.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::mkdir().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
+  @trigger_error('drupal_mkdir() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::mkdir(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->mkdir($uri, $mode, $recursive, $context);
 }
 
 /**
  * Removes a directory.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::rmdir().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_rmdir($uri, $context = NULL) {
+  @trigger_error('drupal_rmdir() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::rmdir(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->rmdir($uri, $context);
 }
 
 /**
  * Creates a file with a unique filename in the specified directory.
  *
- * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
+ * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  *   Use \Drupal\Core\File\FileSystem::tempnam().
  *
  * @see https://www.drupal.org/node/2418133
  */
 function drupal_tempnam($directory, $prefix) {
+  @trigger_error('tempnam() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::tempnam(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
   return \Drupal::service('file_system')->tempnam($directory, $prefix);
 }
 
diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc
index 18f6a398bf3f..48cc8fe50f92 100644
--- a/core/includes/install.core.inc
+++ b/core/includes/install.core.inc
@@ -1444,9 +1444,11 @@ function install_download_translation(&$install_state) {
  */
 function install_retrieve_file($uri, $destination) {
   $parsed_url = parse_url($uri);
-  if (is_dir(\Drupal::service('file_system')->realpath($destination))) {
+  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+  $file_system = \Drupal::service('file_system');
+  if (is_dir($file_system->realpath($destination))) {
     // Prevent URIs with triple slashes when gluing parts together.
-    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
+    $path = str_replace('///', '//', "$destination/") . $file_system->basename($parsed_url['path']);
   }
   else {
     $path = $destination;
diff --git a/core/includes/install.inc b/core/includes/install.inc
index 45a8b141c3be..70c82b4c853f 100644
--- a/core/includes/install.inc
+++ b/core/includes/install.inc
@@ -781,7 +781,7 @@ function drupal_install_mkdir($file, $mask, $message = TRUE) {
     }
   }
 
-  if (@drupal_mkdir($file, $mod)) {
+  if (@\Drupal::service('file_system')->mkdir($file, $mod)) {
     return TRUE;
   }
   else {
diff --git a/core/lib/Drupal/Core/Config/FileStorage.php b/core/lib/Drupal/Core/Config/FileStorage.php
index 518da73a7f38..3de62fdd92db 100644
--- a/core/lib/Drupal/Core/Config/FileStorage.php
+++ b/core/lib/Drupal/Core/Config/FileStorage.php
@@ -156,7 +156,7 @@ public function write($name, array $data) {
       throw new StorageException('Failed to write configuration file: ' . $this->getFilePath($name));
     }
     else {
-      drupal_chmod($target);
+      \Drupal::service('file_system')->chmod($target);
     }
 
     $this->fileCache->set($target, $data);
@@ -248,7 +248,7 @@ public function deleteAll($prefix = '') {
     if ($success && $this->collection != StorageInterface::DEFAULT_COLLECTION) {
       // Remove empty directories.
       if (!(new \FilesystemIterator($this->getCollectionDirectory()))->valid()) {
-        drupal_rmdir($this->getCollectionDirectory());
+        \Drupal::service('file_system')->rmdir($this->getCollectionDirectory());
       }
     }
     return $success;
diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
index ef0dd8680aee..fe007cfe0511 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
@@ -386,7 +386,7 @@ public function databaseType() {
   public function createDatabase($database) {
     // Verify the database is writable.
     $db_directory = new \SplFileInfo(dirname($database));
-    if (!$db_directory->isDir() && !drupal_mkdir($db_directory->getPathName(), 0755, TRUE)) {
+    if (!$db_directory->isDir() && !\Drupal::service('file_system')->mkdir($db_directory->getPathName(), 0755, TRUE)) {
       throw new DatabaseNotFoundException('Unable to create database directory ' . $db_directory->getPathName());
     }
   }
diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Install/Tasks.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Install/Tasks.php
index f5cb289329f5..dacf5b99fbe7 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Install/Tasks.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Install/Tasks.php
@@ -68,7 +68,7 @@ protected function connect() {
 
         // We cannot use file_directory_temp() here because we haven't yet
         // successfully connected to the database.
-        $connection_info['default']['database'] = drupal_tempnam(sys_get_temp_dir(), 'sqlite');
+        $connection_info['default']['database'] = \Drupal::service('file_system')->tempnam(sys_get_temp_dir(), 'sqlite');
 
         // In order to change the Database::$databaseInfo array, need to remove
         // the active connection, then re-add it with the new info.
diff --git a/core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php b/core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php
index 54a60e1866c6..056f62792faa 100644
--- a/core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php
+++ b/core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php
@@ -897,7 +897,7 @@ public function guess($path) {
     }
 
     $extension = '';
-    $file_parts = explode('.', drupal_basename($path));
+    $file_parts = explode('.', \Drupal::service('file_system')->basename($path));
 
     // Remove the first part: a full filename should not match an extension.
     array_shift($file_parts);
diff --git a/core/lib/Drupal/Core/FileTransfer/FileTransfer.php b/core/lib/Drupal/Core/FileTransfer/FileTransfer.php
index 96eb175ab96d..9e4148824efb 100644
--- a/core/lib/Drupal/Core/FileTransfer/FileTransfer.php
+++ b/core/lib/Drupal/Core/FileTransfer/FileTransfer.php
@@ -272,7 +272,7 @@ public function sanitizePath($path) {
    */
   protected function copyDirectoryJailed($source, $destination) {
     if ($this->isDirectory($destination)) {
-      $destination = $destination . '/' . drupal_basename($source);
+      $destination = $destination . '/' . \Drupal::service('file_system')->basename($source);
     }
     $this->createDirectory($destination);
     foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $filename => $file) {
@@ -364,7 +364,7 @@ public function findChroot() {
     $chroot = '';
     while (count($parts)) {
       $check = implode($parts, '/');
-      if ($this->isFile($check . '/' . drupal_basename(__FILE__))) {
+      if ($this->isFile($check . '/' . \Drupal::service('file_system')->basename(__FILE__))) {
         // Remove the trailing slash.
         return substr($chroot, 0, -1);
       }
diff --git a/core/lib/Drupal/Core/FileTransfer/Local.php b/core/lib/Drupal/Core/FileTransfer/Local.php
index 1da4e48eaa75..82ee421ba821 100644
--- a/core/lib/Drupal/Core/FileTransfer/Local.php
+++ b/core/lib/Drupal/Core/FileTransfer/Local.php
@@ -47,9 +47,11 @@ protected function removeDirectoryJailed($directory) {
       // Programmer error assertion, not something we expect users to see.
       throw new FileTransferException('removeDirectoryJailed() called with a path (%directory) that is not a directory.', NULL, ['%directory' => $directory]);
     }
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
     foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST) as $filename => $file) {
       if ($file->isDir()) {
-        if (@!drupal_rmdir($filename)) {
+        if (@!$file_system->rmdir($filename)) {
           throw new FileTransferException('Cannot remove directory %directory.', NULL, ['%directory' => $filename]);
         }
       }
@@ -59,7 +61,7 @@ protected function removeDirectoryJailed($directory) {
         }
       }
     }
-    if (@!drupal_rmdir($directory)) {
+    if (@!$file_system->rmdir($directory)) {
       throw new FileTransferException('Cannot remove directory %directory.', NULL, ['%directory' => $directory]);
     }
   }
diff --git a/core/lib/Drupal/Core/Image/Image.php b/core/lib/Drupal/Core/Image/Image.php
index e4c787632f5b..864ea82a5ca5 100644
--- a/core/lib/Drupal/Core/Image/Image.php
+++ b/core/lib/Drupal/Core/Image/Image.php
@@ -128,8 +128,7 @@ public function save($destination = NULL) {
       $this->fileSize = filesize($destination);
       $this->source = $destination;
 
-      // @todo Use File utility when https://www.drupal.org/node/2050759 is in.
-      if ($this->chmod($destination)) {
+      if (\Drupal::service('file_system')->chmod($destination)) {
         return $return;
       }
     }
@@ -208,15 +207,18 @@ public function scale($width, $height = NULL, $upscale = FALSE) {
    *   Integer value for the permissions. Consult PHP chmod() documentation for
    *   more information.
    *
-   * @see drupal_chmod()
-   *
-   * @todo Remove when https://www.drupal.org/node/2050759 is in.
-   *
    * @return bool
    *   TRUE for success, FALSE in the event of an error.
+   *
+   * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
+   *   Use \Drupal\Core\File\FileSystem::chmod().
+   *
+   * @see \Drupal\Core\File\FileSystemInterface::chmod()
+   * @see https://www.drupal.org/node/2418133
    */
   protected function chmod($uri, $mode = NULL) {
-    return drupal_chmod($uri, $mode);
+    @trigger_error('chmod() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::chmod(). See https://www.drupal.org/node/2418133.', E_USER_DEPRECATED);
+    return \Drupal::service('file_system')->chmod($uri, $mode);
   }
 
 }
diff --git a/core/lib/Drupal/Core/StreamWrapper/LocalStream.php b/core/lib/Drupal/Core/StreamWrapper/LocalStream.php
index 20b2712c7635..b139b7825ea5 100644
--- a/core/lib/Drupal/Core/StreamWrapper/LocalStream.php
+++ b/core/lib/Drupal/Core/StreamWrapper/LocalStream.php
@@ -134,7 +134,7 @@ protected function getLocalPath($uri = NULL) {
     $realpath = realpath($path);
     if (!$realpath) {
       // This file does not yet exist.
-      $realpath = realpath(dirname($path)) . '/' . drupal_basename($path);
+      $realpath = realpath(dirname($path)) . '/' . \Drupal::service('file_system')->basename($path);
     }
     $directory = realpath($this->getDirectoryPath());
     if (!$realpath || !$directory || strpos($realpath, $directory) !== 0) {
@@ -397,9 +397,9 @@ public function rename($from_uri, $to_uri) {
   /**
    * Gets the name of the directory from a given path.
    *
-   * This method is usually accessed through drupal_dirname(), which wraps
-   * around the PHP dirname() function because it does not support stream
-   * wrappers.
+   * This method is usually accessed through
+   * \Drupal\Core\File\FileSystemInterface::dirname(), which wraps around the
+   * PHP dirname() function because it does not support stream wrappers.
    *
    * @param string $uri
    *   A URI or path.
@@ -407,7 +407,7 @@ public function rename($from_uri, $to_uri) {
    * @return string
    *   A string containing the directory name.
    *
-   * @see drupal_dirname()
+   * @see \Drupal\Core\File\FileSystemInterface::dirname()
    */
   public function dirname($uri = NULL) {
     list($scheme) = explode('://', $uri, 2);
@@ -447,11 +447,13 @@ public function mkdir($uri, $mode, $options) {
     else {
       $localpath = $this->getLocalPath($uri);
     }
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
     if ($options & STREAM_REPORT_ERRORS) {
-      return drupal_mkdir($localpath, $mode, $recursive);
+      return $file_system->mkdir($localpath, $mode, $recursive);
     }
     else {
-      return @drupal_mkdir($localpath, $mode, $recursive);
+      return @$file_system->mkdir($localpath, $mode, $recursive);
     }
   }
 
@@ -470,11 +472,13 @@ public function mkdir($uri, $mode, $options) {
    */
   public function rmdir($uri, $options) {
     $this->uri = $uri;
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
     if ($options & STREAM_REPORT_ERRORS) {
-      return drupal_rmdir($this->getLocalPath());
+      return $file_system->rmdir($this->getLocalPath());
     }
     else {
-      return @drupal_rmdir($this->getLocalPath());
+      return @$file_system->rmdir($this->getLocalPath());
     }
   }
 
diff --git a/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php b/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php
index 84ab52c8c013..a354785affbd 100644
--- a/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php
+++ b/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php
@@ -167,9 +167,9 @@ public function realpath();
   /**
    * Gets the name of the directory from a given path.
    *
-   * This method is usually accessed through drupal_dirname(), which wraps
-   * around the normal PHP dirname() function, which does not support stream
-   * wrappers.
+   * This method is usually accessed through
+   * \Drupal\Core\File\FileSystemInterface::dirname(), which wraps around the
+   * normal PHP dirname() function, which does not support stream wrappers.
    *
    * @param string $uri
    *   An optional URI.
@@ -177,7 +177,7 @@ public function realpath();
    * @return string
    *   A string containing the directory name, or FALSE if not applicable.
    *
-   * @see drupal_dirname()
+   * @see \Drupal\Core\File\FileSystemInterface::dirname()
    */
   public function dirname($uri = NULL);
 
diff --git a/core/lib/Drupal/Core/Updater/Updater.php b/core/lib/Drupal/Core/Updater/Updater.php
index c8b35f8ce9d3..ff673aa74eb3 100644
--- a/core/lib/Drupal/Core/Updater/Updater.php
+++ b/core/lib/Drupal/Core/Updater/Updater.php
@@ -111,7 +111,7 @@ public static function findInfoFile($directory) {
       return FALSE;
     }
     foreach ($info_files as $info_file) {
-      if (mb_substr($info_file->filename, 0, -9) == drupal_basename($directory)) {
+      if (mb_substr($info_file->filename, 0, -9) == \Drupal::service('file_system')->basename($directory)) {
         // Info file Has the same name as the directory, return it.
         return $info_file->uri;
       }
@@ -155,7 +155,7 @@ protected static function getExtensionInfo($directory) {
    *   The name of the project.
    */
   public static function getProjectName($directory) {
-    return drupal_basename($directory);
+    return \Drupal::service('file_system')->basename($directory);
   }
 
   /**
diff --git a/core/modules/color/color.module b/core/modules/color/color.module
index 140890aff46e..b375661be01e 100644
--- a/core/modules/color/color.module
+++ b/core/modules/color/color.module
@@ -88,7 +88,9 @@ function color_library_info_alter(&$libraries, $extension) {
               foreach ($color_paths as $color_path) {
                 // Color module currently requires unique file names to be used,
                 // which allows us to compare different file paths.
-                if (drupal_basename($path) == drupal_basename($color_path)) {
+                /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+                $file_system = \Drupal::service('file_system');
+                if ($file_system->basename($path) == $file_system->basename($color_path)) {
                   // Replace the path to the new css file.
                   // This keeps the order of the stylesheets intact.
                   $index = array_search($path, array_keys($libraries[$name]['css'][$category]));
@@ -429,7 +431,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) {
     }
   }
   if (isset($file) && $file = dirname($file)) {
-    @drupal_rmdir($file);
+    @\Drupal::service('file_system')->rmdir($file);
   }
 
   // No change in color config, use the standard theme from color.inc.
@@ -459,8 +461,10 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) {
     ->save();
 
   // Copy over neutral images.
+  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+  $file_system = \Drupal::service('file_system');
   foreach ($info['copy'] as $file) {
-    $base = drupal_basename($file);
+    $base = $file_system->basename($file);
     $source = $paths['source'] . $file;
     try {
       $filepath = $file_system->copy($source, $paths['target'] . $base);
@@ -502,7 +506,7 @@ function color_scheme_form_submit($form, FormStateInterface $form_state) {
 
       // Rewrite stylesheet with new colors.
       $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
-      $base_file = drupal_basename($file);
+      $base_file = $file_system->basename($file);
       $css[] = $paths['target'] . $base_file;
       _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
     }
@@ -595,7 +599,7 @@ function _color_save_stylesheet($file, $style, &$paths) {
   $paths['files'][] = $filepath;
 
   // Set standard file permissions for webserver-generated files.
-  drupal_chmod($file);
+  \Drupal::service('file_system')->chmod($file);
 }
 
 /**
@@ -645,8 +649,10 @@ function _color_render_images($theme, &$info, &$paths, $palette) {
   // Cut out slices.
   foreach ($info['slices'] as $file => $coord) {
     list($x, $y, $width, $height) = $coord;
-    $base = drupal_basename($file);
-    $image = \Drupal::service('file_system')->realpath($paths['target'] . $base);
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $base = $file_system->basename($file);
+    $image = $file_system->realpath($paths['target'] . $base);
 
     // Cut out slice.
     if ($file == 'screenshot.png') {
@@ -666,8 +672,8 @@ function _color_render_images($theme, &$info, &$paths, $palette) {
     imagedestroy($slice);
     $paths['files'][] = $image;
 
-    // Set standard file permissions for webserver-generated files
-    drupal_chmod($image);
+    // Set standard file permissions for webserver-generated files.
+    $file_system->chmod($image);
 
     // Build before/after map of image paths.
     $paths['map'][$file] = $base;
diff --git a/core/modules/editor/tests/src/Kernel/EditorFileUsageTest.php b/core/modules/editor/tests/src/Kernel/EditorFileUsageTest.php
index aac665d61b5c..13cfe5e9a212 100644
--- a/core/modules/editor/tests/src/Kernel/EditorFileUsageTest.php
+++ b/core/modules/editor/tests/src/Kernel/EditorFileUsageTest.php
@@ -73,7 +73,7 @@ public function testEditorEntityHooks() {
     foreach ($image_paths as $key => $image_path) {
       $image = File::create();
       $image->setFileUri($image_path);
-      $image->setFilename(drupal_basename($image->getFileUri()));
+      $image->setFilename(\Drupal::service('file_system')->basename($image->getFileUri()));
       $image->save();
 
       $file_usage = $this->container->get('file.usage');
diff --git a/core/modules/file/file.module b/core/modules/file/file.module
index 93fed7a4b405..6e812bca744c 100644
--- a/core/modules/file/file.module
+++ b/core/modules/file/file.module
@@ -172,7 +172,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E
     $uri = $file_system->copy($source->getFileUri(), $destination, $replace);
     $file = $source->createDuplicate();
     $file->setFileUri($uri);
-    $file->setFilename(drupal_basename($uri));
+    $file->setFilename($file_system->basename($uri));
     // If we are replacing an existing file re-use its database record.
     // @todo Do not create a new entity in order to update it. See
     //   https://www.drupal.org/node/2241865.
@@ -188,7 +188,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E
     // If we are renaming around an existing file (rather than a directory),
     // use its basename for the filename.
     elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
-      $file->setFilename(drupal_basename($destination));
+      $file->setFilename($file_system->basename($destination));
     }
 
     $file->save();
@@ -267,7 +267,7 @@ function file_move(FileInterface $source, $destination = NULL, $replace = FILE_E
     // If we are renaming around an existing file (rather than a directory),
     // use its basename for the filename.
     elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
-      $file->setFilename(drupal_basename($destination));
+      $file->setFilename(\Drupal::service('file_system')->basename($destination));
     }
 
     $file->save();
@@ -590,7 +590,7 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM
     // If we are renaming around an existing file (rather than a directory),
     // use its basename for the filename.
     elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
-      $file->setFilename(drupal_basename($destination));
+      $file->setFilename(\Drupal::service('file_system')->basename($destination));
     }
 
     $file->save();
@@ -1078,7 +1078,7 @@ function _file_save_upload_single(\SplFileInfo $file_info, $form_field_name, $va
   }
 
   // Set the permissions on the new file.
-  drupal_chmod($file->getFileUri());
+  $file_system->chmod($file->getFileUri());
 
   // If we are replacing an existing file re-use its database record.
   // @todo Do not create a new entity in order to update it. See
diff --git a/core/modules/file/src/Entity/File.php b/core/modules/file/src/Entity/File.php
index d8aab938361a..9eccd88eaf94 100644
--- a/core/modules/file/src/Entity/File.php
+++ b/core/modules/file/src/Entity/File.php
@@ -165,7 +165,7 @@ public function setTemporary() {
   public static function preCreate(EntityStorageInterface $storage, array &$values) {
     // Automatically detect filename if not set.
     if (!isset($values['filename']) && isset($values['uri'])) {
-      $values['filename'] = drupal_basename($values['uri']);
+      $values['filename'] = \Drupal::service('file_system')->basename($values['uri']);
     }
 
     // Automatically detect filemime if not set.
diff --git a/core/modules/file/tests/src/Functional/FileTokenReplaceTest.php b/core/modules/file/tests/src/Functional/FileTokenReplaceTest.php
index 2ccb77ea91f9..689b1206b43d 100644
--- a/core/modules/file/tests/src/Functional/FileTokenReplaceTest.php
+++ b/core/modules/file/tests/src/Functional/FileTokenReplaceTest.php
@@ -31,7 +31,7 @@ public function testFileTokenReplacement() {
 
     $test_file = $this->getTestFile('text');
     // Coping a file to test uploads with non-latin filenames.
-    $filename = drupal_dirname($test_file->getFileUri()) . '/текстовый файл.txt';
+    $filename = \Drupal::service('file_system')->dirname($test_file->getFileUri()) . '/текстовый файл.txt';
     $test_file = file_copy($test_file, $filename);
 
     // Create a new node with the uploaded file.
diff --git a/core/modules/file/tests/src/Functional/SaveUploadFormTest.php b/core/modules/file/tests/src/Functional/SaveUploadFormTest.php
index a9b3aca2049b..ee1168c42ac8 100644
--- a/core/modules/file/tests/src/Functional/SaveUploadFormTest.php
+++ b/core/modules/file/tests/src/Functional/SaveUploadFormTest.php
@@ -134,7 +134,7 @@ public function testNormal() {
     $this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('You WIN!'));
-    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
+    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(\Drupal::service('file_system')->basename($image3_realpath))));
   }
 
   /**
@@ -364,7 +364,7 @@ public function testNoUpload() {
   public function testDrupalMovingUploadedFileError() {
     // Create a directory and make it not writable.
     $test_directory = 'test_drupal_move_uploaded_file_fail';
-    drupal_mkdir('temporary://' . $test_directory, 0000);
+    \Drupal::service('file_system')->mkdir('temporary://' . $test_directory, 0000);
     $this->assertTrue(is_dir('temporary://' . $test_directory));
 
     /** @var \Drupal\Core\File\FileSystemInterface $file_system */
diff --git a/core/modules/file/tests/src/Functional/SaveUploadTest.php b/core/modules/file/tests/src/Functional/SaveUploadTest.php
index ea1ac109f1f6..d8e66b7e1777 100644
--- a/core/modules/file/tests/src/Functional/SaveUploadTest.php
+++ b/core/modules/file/tests/src/Functional/SaveUploadTest.php
@@ -125,7 +125,7 @@ public function testNormal() {
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('You WIN!'));
-    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
+    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(\Drupal::service('file_system')->basename($image3_realpath))));
   }
 
   /**
@@ -346,12 +346,14 @@ public function testNoUpload() {
   public function testDrupalMovingUploadedFileError() {
     // Create a directory and make it not writable.
     $test_directory = 'test_drupal_move_uploaded_file_fail';
-    drupal_mkdir('temporary://' . $test_directory, 0000);
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $file_system->mkdir('temporary://' . $test_directory, 0000);
     $this->assertTrue(is_dir('temporary://' . $test_directory));
 
     $edit = [
       'file_subdir' => $test_directory,
-      'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
+      'files[file_test_upload]' => $file_system->realpath($this->image->getFileUri()),
     ];
 
     \Drupal::state()->set('file_test.disable_error_collection', TRUE);
diff --git a/core/modules/file/tests/src/Kernel/SaveDataTest.php b/core/modules/file/tests/src/Kernel/SaveDataTest.php
index 8d03e3656d02..1b7b9b0fbd6a 100644
--- a/core/modules/file/tests/src/Kernel/SaveDataTest.php
+++ b/core/modules/file/tests/src/Kernel/SaveDataTest.php
@@ -21,7 +21,7 @@ public function testWithoutFilename() {
     $this->assertTrue($result, 'Unnamed file saved correctly.');
 
     $this->assertEqual(file_default_scheme(), file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
-    $this->assertEqual($result->getFilename(), drupal_basename($result->getFileUri()), "Filename was set to the file's basename.");
+    $this->assertEqual($result->getFilename(), \Drupal::service('file_system')->basename($result->getFileUri()), "Filename was set to the file's basename.");
     $this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
     $this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
     $this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
@@ -46,7 +46,7 @@ public function testWithFilename() {
     $this->assertTrue($result, 'Unnamed file saved correctly.');
 
     $this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
-    $this->assertEqual($filename, drupal_basename($result->getFileUri()), 'File was named correctly.');
+    $this->assertEqual($filename, \Drupal::service('file_system')->basename($result->getFileUri()), 'File was named correctly.');
     $this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
     $this->assertEqual($result->getMimeType(), 'text/plain', 'A MIME type was set.');
     $this->assertTrue($result->isPermanent(), "The file's status was set to permanent.");
diff --git a/core/modules/file/tests/src/Kernel/ValidatorTest.php b/core/modules/file/tests/src/Kernel/ValidatorTest.php
index ab0d85229c75..9f6dde314bdb 100644
--- a/core/modules/file/tests/src/Kernel/ValidatorTest.php
+++ b/core/modules/file/tests/src/Kernel/ValidatorTest.php
@@ -30,11 +30,13 @@ protected function setUp() {
 
     $this->image = File::create();
     $this->image->setFileUri('core/misc/druplicon.png');
-    $this->image->setFilename(drupal_basename($this->image->getFileUri()));
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $this->image->setFilename($file_system->basename($this->image->getFileUri()));
 
     $this->nonImage = File::create();
     $this->nonImage->setFileUri('core/assets/vendor/jquery/jquery.min.js');
-    $this->nonImage->setFilename(drupal_basename($this->nonImage->getFileUri()));
+    $this->nonImage->setFilename($file_system->basename($this->nonImage->getFileUri()));
   }
 
   /**
diff --git a/core/modules/image/src/Entity/ImageStyle.php b/core/modules/image/src/Entity/ImageStyle.php
index 5a8667dc84b2..3baded7cee73 100644
--- a/core/modules/image/src/Entity/ImageStyle.php
+++ b/core/modules/image/src/Entity/ImageStyle.php
@@ -304,7 +304,7 @@ public function createDerivative($original_uri, $derivative_uri) {
     }
 
     // Get the folder for the final location of this style.
-    $directory = drupal_dirname($derivative_uri);
+    $directory = \Drupal::service('file_system')->dirname($derivative_uri);
 
     // Build the destination folder tree if it doesn't already exist.
     if (!\Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
diff --git a/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php b/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
index 2c47b0aa4687..ba4677d7ea0b 100644
--- a/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
+++ b/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
@@ -344,10 +344,10 @@ public static function generateSampleValue(FieldDefinitionInterface $field_defin
     $extension = array_rand(array_combine($extensions, $extensions));
     // Generate a max of 5 different images.
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) {
-      $tmp_file = drupal_tempnam('temporary://', 'generateImage_');
-      $destination = $tmp_file . '.' . $extension;
       /** @var \Drupal\Core\File\FileSystemInterface $file_system */
       $file_system = \Drupal::service('file_system');
+      $tmp_file = $file_system->tempnam('temporary://', 'generateImage_');
+      $destination = $tmp_file . '.' . $extension;
       try {
         $file_system->move($tmp_file, $destination);
       }
@@ -359,7 +359,7 @@ public static function generateSampleValue(FieldDefinitionInterface $field_defin
         $image->setFileUri($path);
         $image->setOwnerId(\Drupal::currentUser()->id());
         $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path));
-        $image->setFileName(drupal_basename($path));
+        $image->setFileName($file_system->basename($path));
         $destination_dir = static::doGetUploadLocation($settings);
         $file_system->prepareDirectory($destination_dir, FileSystemInterface::CREATE_DIRECTORY);
         $destination = $destination_dir . '/' . basename($path);
diff --git a/core/modules/image/tests/src/Functional/ImageStylesPathAndUrlTest.php b/core/modules/image/tests/src/Functional/ImageStylesPathAndUrlTest.php
index 69cb5d8c7816..4a9e57d83d6b 100644
--- a/core/modules/image/tests/src/Functional/ImageStylesPathAndUrlTest.php
+++ b/core/modules/image/tests/src/Functional/ImageStylesPathAndUrlTest.php
@@ -235,7 +235,7 @@ public function doImageStyleUrlAndPathTests($scheme, $clean_url = TRUE, $extra_s
       // make sure that access is denied.
       $file_noaccess = array_shift($files);
       $original_uri_noaccess = $file_system->copy($file_noaccess->uri, $scheme . '://', FileSystemInterface::EXISTS_RENAME);
-      $generated_uri_noaccess = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . drupal_basename($original_uri_noaccess);
+      $generated_uri_noaccess = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . $file_system->basename($original_uri_noaccess);
       $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
       $generate_url_noaccess = $this->style->buildUrl($original_uri_noaccess);
 
diff --git a/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php b/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php
index 976f892f6829..26b0883717b8 100644
--- a/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php
+++ b/core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php
@@ -83,7 +83,7 @@ public function testUILanguageNegotiation() {
     $http_header_blah = ["Accept-Language" => "blah;q=1"];
 
     // Create a private file for testing accessible by the admin user.
-    drupal_mkdir($this->privateFilesDirectory . '/test');
+    \Drupal::service('file_system')->mkdir($this->privateFilesDirectory . '/test');
     $filepath = 'private://test/private-file-test.txt';
     $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
     file_put_contents($filepath, $contents);
diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc
index 1b9031f245c2..e236acf30ca7 100644
--- a/core/modules/locale/locale.bulk.inc
+++ b/core/modules/locale/locale.bulk.inc
@@ -426,7 +426,7 @@ function locale_translate_batch_finished($success, array $results) {
  */
 function locale_translate_file_create($filepath) {
   $file = new stdClass();
-  $file->filename = drupal_basename($filepath);
+  $file->filename = \Drupal::service('file_system')->basename($filepath);
   $file->uri = $filepath;
   $file->timestamp = filemtime($file->uri);
   return $file;
diff --git a/core/modules/locale/locale.install b/core/modules/locale/locale.install
index 94117df1fa6f..6321457686b2 100644
--- a/core/modules/locale/locale.install
+++ b/core/modules/locale/locale.install
@@ -44,7 +44,7 @@ function locale_uninstall() {
     }
     // Delete the JavaScript translations directory if empty.
     if (!file_scan_directory($locale_js_directory, '/.*/')) {
-      drupal_rmdir($locale_js_directory);
+      \Drupal::service('file_system')->rmdir($locale_js_directory);
     }
   }
 
diff --git a/core/modules/locale/locale.translation.inc b/core/modules/locale/locale.translation.inc
index 9d7bfd6e83f8..1b1cdb761682 100644
--- a/core/modules/locale/locale.translation.inc
+++ b/core/modules/locale/locale.translation.inc
@@ -271,7 +271,7 @@ function locale_translation_source_build($project, $langcode, $filename = NULL)
       'version' => $project->version,
       'type' => LOCALE_TRANSLATION_LOCAL,
       'filename' => locale_translation_build_server_pattern($source, basename($source->server_pattern)),
-      'directory' => locale_translation_build_server_pattern($source, drupal_dirname($source->server_pattern)),
+      'directory' => locale_translation_build_server_pattern($source, \Drupal::service('file_system')->dirname($source->server_pattern)),
     ];
     $files[LOCALE_TRANSLATION_LOCAL]->uri = $files[LOCALE_TRANSLATION_LOCAL]->directory . '/' . $files[LOCALE_TRANSLATION_LOCAL]->filename;
   }
diff --git a/core/modules/simpletest/src/Tests/SimpleTestErrorCollectorTest.php b/core/modules/simpletest/src/Tests/SimpleTestErrorCollectorTest.php
index 61bd5432b4db..0c9fc2d41bd4 100644
--- a/core/modules/simpletest/src/Tests/SimpleTestErrorCollectorTest.php
+++ b/core/modules/simpletest/src/Tests/SimpleTestErrorCollectorTest.php
@@ -85,7 +85,7 @@ protected function error($message = '', $group = 'Other', array $caller = NULL)
   public function assertError($error, $group, $function, $file, $message = NULL) {
     $this->assertEqual($error['group'], $group, format_string("Group was %group", ['%group' => $group]));
     $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", ['%function' => $function]));
-    $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", ['%file' => $file]));
+    $this->assertEqual(\Drupal::service('file_system')->basename($error['caller']['file']), $file, format_string("File was %file", ['%file' => $file]));
     if (isset($message)) {
       $this->assertEqual($error['message'], $message, format_string("Message was %message", ['%message' => $message]));
     }
diff --git a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
index e1512f172035..d5cf58c5e8a0 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
@@ -237,7 +237,7 @@ public function save($destination) {
       $local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
       if (!isset($local_wrappers[$scheme])) {
         $permanent_destination = $destination;
-        $destination = drupal_tempnam('temporary://', 'gd_');
+        $destination = $this->fileSystem->tempnam('temporary://', 'gd_');
       }
       // Convert stream wrapper URI to normal path.
       $destination = $this->fileSystem->realpath($destination);
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index 91fa9f514217..57f297bb4a13 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -919,13 +919,15 @@ function system_check_directory($form_element, FormStateInterface $form_state) {
   }
 
   $logger = \Drupal::logger('file system');
-  if (!is_dir($directory) && !drupal_mkdir($directory, NULL, TRUE)) {
+  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+  $file_system = \Drupal::service('file_system');
+  if (!is_dir($directory) && !$file_system->mkdir($directory, NULL, TRUE)) {
     // If the directory does not exist and cannot be created.
     $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory does not exist and could not be created.', ['%directory' => $directory]));
     $logger->error('The directory %directory does not exist and could not be created.', ['%directory' => $directory]);
   }
 
-  if (is_dir($directory) && !is_writable($directory) && !drupal_chmod($directory)) {
+  if (is_dir($directory) && !is_writable($directory) && !$file_system->chmod($directory)) {
     // If the directory is not writable and cannot be made so.
     $form_state->setErrorByName($form_element['#parents'][0], t('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]));
     $logger->error('The directory %directory exists but is not writable and could not be made writable.', ['%directory' => $directory]);
@@ -1337,12 +1339,12 @@ function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $repl
   /** @var \Drupal\Core\File\FileSystemInterface $file_system */
   $file_system = \Drupal::service('file_system');
   if (!isset($destination)) {
-    $path = file_build_uri(drupal_basename($parsed_url['path']));
+    $path = file_build_uri(\Drupal::service('file_system')->basename($parsed_url['path']));
   }
   else {
     if (is_dir($file_system->realpath($destination))) {
       // Prevent URIs with triple slashes when glueing parts together.
-      $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
+      $path = str_replace('///', '//', "$destination/") . \Drupal::service('file_system')->basename($parsed_url['path']);
     }
     else {
       $path = $destination;
diff --git a/core/modules/system/tests/src/Functional/System/RetrieveFileTest.php b/core/modules/system/tests/src/Functional/System/RetrieveFileTest.php
index dfe9a5bb0b33..bcd8f7d3bfb3 100644
--- a/core/modules/system/tests/src/Functional/System/RetrieveFileTest.php
+++ b/core/modules/system/tests/src/Functional/System/RetrieveFileTest.php
@@ -16,7 +16,9 @@ class RetrieveFileTest extends BrowserTestBase {
    */
   public function testFileRetrieving() {
     // Test 404 handling by trying to fetch a randomly named file.
-    drupal_mkdir($sourcedir = 'public://' . $this->randomMachineName());
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $file_system->mkdir($sourcedir = 'public://' . $this->randomMachineName());
     $filename = 'Файл для тестирования ' . $this->randomMachineName();
     $url = file_create_url($sourcedir . '/' . $filename);
     $retrieved_file = system_retrieve_file($url);
@@ -38,7 +40,7 @@ public function testFileRetrieving() {
     $file_system->delete($retrieved_file);
 
     // Test downloading file to a different location.
-    drupal_mkdir($targetdir = 'temporary://' . $this->randomMachineName());
+    $file_system->mkdir($targetdir = 'temporary://' . $this->randomMachineName());
     $retrieved_file = system_retrieve_file($url, $targetdir);
     $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
     $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
diff --git a/core/modules/update/update.manager.inc b/core/modules/update/update.manager.inc
index 61edc15cf92d..2b2aef2ff9f7 100644
--- a/core/modules/update/update.manager.inc
+++ b/core/modules/update/update.manager.inc
@@ -219,7 +219,7 @@ function update_manager_file_get($url) {
 
   // Check the cache and download the file if needed.
   $cache_directory = _update_manager_cache_directory();
-  $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
+  $local = $cache_directory . '/' . \Drupal::service('file_system')->basename($parsed_url['path']);
 
   if (!file_exists($local) || update_delete_file_if_stale($local)) {
     return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
@@ -311,7 +311,7 @@ function update_manager_local_transfers_allowed() {
   // Compare the owner of a webserver-created temporary file to the owner of
   // the configuration directory to determine if local transfers will be
   // allowed.
-  $temporary_file = drupal_tempnam('temporary://', 'update_');
+  $temporary_file = \Drupal::service('file_system')->tempnam('temporary://', 'update_');
   $site_path = \Drupal::service('site.path');
   $local_transfers_allowed = fileowner($temporary_file) === fileowner($site_path);
 
diff --git a/core/modules/update/update.module b/core/modules/update/update.module
index a4f32929c070..8a4a2cedc5b7 100644
--- a/core/modules/update/update.module
+++ b/core/modules/update/update.module
@@ -705,15 +705,21 @@ function update_verify_update_archive($project, $archive_file, $directory) {
     }
   }
 
+  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+  $file_system = \Drupal::service('file_system');
   if (empty($files)) {
-    $errors[] = t('%archive_file does not contain any .info.yml files.', ['%archive_file' => drupal_basename($archive_file)]);
+    $errors[] = t('%archive_file does not contain any .info.yml files.', ['%archive_file' => $file_system->basename($archive_file)]);
   }
   elseif (!$compatible_project) {
     $errors[] = \Drupal::translation()->formatPlural(
       count($incompatible),
       '%archive_file contains a version of %names that is not compatible with Drupal @version.',
       '%archive_file contains versions of modules or themes that are not compatible with Drupal @version: %names',
-      ['@version' => \Drupal::CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible)]
+      [
+        '@version' => \Drupal::CORE_COMPATIBILITY,
+        '%archive_file' => $file_system->basename($archive_file),
+        '%names' => implode(', ', $incompatible),
+      ]
     );
   }
 
diff --git a/core/tests/Drupal/KernelTests/Core/File/DirectoryTest.php b/core/tests/Drupal/KernelTests/Core/File/DirectoryTest.php
index 80ef82c070f3..5abfb060bfe8 100644
--- a/core/tests/Drupal/KernelTests/Core/File/DirectoryTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/DirectoryTest.php
@@ -32,7 +32,9 @@ public function testFileCheckLocalDirectoryHandling() {
     // Create the directories.
     $parent_path = $directory . DIRECTORY_SEPARATOR . $parent;
     $child_path = $parent_path . DIRECTORY_SEPARATOR . $child;
-    $this->assertTrue(drupal_mkdir($child_path, 0775, TRUE), t('No error reported when creating new local directories.'), 'File');
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $this->assertTrue($file_system->mkdir($child_path, 0775, TRUE), t('No error reported when creating new local directories.'), 'File');
 
     // Ensure new directories also exist.
     $this->assertTrue(is_dir($parent_path), t('New parent directory actually exists.'), 'File');
@@ -46,8 +48,8 @@ public function testFileCheckLocalDirectoryHandling() {
     $this->assertDirectoryPermissions($directory, $old_mode);
 
     // Check creating a directory using an absolute path.
-    $absolute_path = \Drupal::service('file_system')->realpath($directory) . DIRECTORY_SEPARATOR . $this->randomMachineName() . DIRECTORY_SEPARATOR . $this->randomMachineName();
-    $this->assertTrue(drupal_mkdir($absolute_path, 0775, TRUE), 'No error reported when creating new absolute directories.', 'File');
+    $absolute_path = $file_system->realpath($directory) . DIRECTORY_SEPARATOR . $this->randomMachineName() . DIRECTORY_SEPARATOR . $this->randomMachineName();
+    $this->assertTrue($file_system->mkdir($absolute_path, 0775, TRUE), 'No error reported when creating new absolute directories.', 'File');
     $this->assertDirectoryPermissions($absolute_path, 0775);
   }
 
@@ -77,7 +79,7 @@ public function testFileCheckDirectoryHandling() {
       // in the directory on any recent version of Windows.
 
       // Make directory read only.
-      @drupal_chmod($directory, 0444);
+      @$file_system->chmod($directory, 0444);
       $this->assertFalse($file_system->prepareDirectory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
 
       // Test directory permission modification.
diff --git a/core/tests/Drupal/KernelTests/Core/File/FileCopyTest.php b/core/tests/Drupal/KernelTests/Core/File/FileCopyTest.php
index 3c9a2017729a..516c4a0673f2 100644
--- a/core/tests/Drupal/KernelTests/Core/File/FileCopyTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/FileCopyTest.php
@@ -81,12 +81,12 @@ public function testOverwriteSelf() {
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
 
     // Copy the file into same directory without renaming fails.
-    $new_filepath = $file_system->copy($uri, drupal_dirname($uri), FileSystemInterface::EXISTS_ERROR);
+    $new_filepath = $file_system->copy($uri, $file_system->dirname($uri), FileSystemInterface::EXISTS_ERROR);
     $this->assertFalse($new_filepath, 'Copying onto itself fails.');
     $this->assertTrue(file_exists($uri), 'File exists after copying onto itself.');
 
     // Copy the file into same directory with renaming works.
-    $new_filepath = $file_system->copy($uri, drupal_dirname($uri), FileSystemInterface::EXISTS_RENAME);
+    $new_filepath = $file_system->copy($uri, $file_system->dirname($uri), FileSystemInterface::EXISTS_RENAME);
     $this->assertTrue($new_filepath, 'Copying into same directory works.');
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
diff --git a/core/tests/Drupal/KernelTests/Core/File/FileSaveDataTest.php b/core/tests/Drupal/KernelTests/Core/File/FileSaveDataTest.php
index b41811232650..75b4c4d0b91e 100644
--- a/core/tests/Drupal/KernelTests/Core/File/FileSaveDataTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/FileSaveDataTest.php
@@ -27,7 +27,7 @@ public function testFileSaveData() {
     // Provide a filename.
     $filepath = $file_system->saveData($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
     $this->assertTrue($filepath, 'Unnamed file saved correctly.');
-    $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
+    $this->assertEqual('asdf.txt', \Drupal::service('file_system')->basename($filepath), 'File was named correctly.');
     $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
     $this->assertFilePermissions($filepath, 0777);
   }
diff --git a/core/tests/Drupal/KernelTests/Core/File/FileSystemDeprecationTest.php b/core/tests/Drupal/KernelTests/Core/File/FileSystemDeprecationTest.php
index 5f2fc570cdab..97112e36bba3 100644
--- a/core/tests/Drupal/KernelTests/Core/File/FileSystemDeprecationTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/FileSystemDeprecationTest.php
@@ -97,4 +97,46 @@ public function testDeprecatedFileUploadMaxSize() {
     $this->assertNotNull(file_upload_max_size());
   }
 
+  /**
+   * @expectedDeprecation drupal_chmod() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::chmod(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalChmod() {
+    $this->assertNotNull(drupal_chmod(''));
+  }
+
+  /**
+   * @expectedDeprecation drupal_dirname() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::dirname(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalDirname() {
+    $this->assertNotNull(drupal_dirname(''));
+  }
+
+  /**
+   * @expectedDeprecation drupal_basename() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::basename(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalBasename() {
+    $this->assertNotNull(drupal_basename(''));
+  }
+
+  /**
+   * @expectedDeprecation drupal_mkdir() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::mkdir(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalMkdir() {
+    $this->assertNotNull(drupal_mkdir('public://test.txt'));
+  }
+
+  /**
+   * @expectedDeprecation drupal_rmdir() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::rmdir(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalRmdir() {
+    $this->assertNotNull(drupal_rmdir('public://test.txt'));
+  }
+
+  /**
+   * @expectedDeprecation tempnam() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::tempnam(). See https://www.drupal.org/node/2418133.
+   */
+  public function testDeprecatedDrupalTempnam() {
+    $this->assertNotNull(drupal_tempnam('temporary://', 'file'));
+  }
+
 }
diff --git a/core/tests/Drupal/KernelTests/Core/File/FileTestBase.php b/core/tests/Drupal/KernelTests/Core/File/FileTestBase.php
index 92612ae7fd44..8add53a3a4fe 100644
--- a/core/tests/Drupal/KernelTests/Core/File/FileTestBase.php
+++ b/core/tests/Drupal/KernelTests/Core/File/FileTestBase.php
@@ -164,7 +164,7 @@ public function createDirectory($path = NULL) {
     if (!isset($path)) {
       $path = file_default_scheme() . '://' . $this->randomMachineName();
     }
-    $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.');
+    $this->assertTrue(\Drupal::service('file_system')->mkdir($path) && is_dir($path), 'Directory was created successfully.');
     return $path;
   }
 
diff --git a/core/tests/Drupal/KernelTests/Core/File/ReadOnlyStreamWrapperTest.php b/core/tests/Drupal/KernelTests/Core/File/ReadOnlyStreamWrapperTest.php
index 00dfa0b8d32f..8dd9de8965cd 100644
--- a/core/tests/Drupal/KernelTests/Core/File/ReadOnlyStreamWrapperTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/ReadOnlyStreamWrapperTest.php
@@ -86,13 +86,15 @@ public function testReadOnlyBehavior() {
     $dirname = $this->randomMachineName();
     $dir = $site_path . '/files/' . $dirname;
     $readonlydir = $this->scheme . '://' . $dirname;
-    $this->assertFalse(@drupal_mkdir($readonlydir, 0775, 0), 'Unable to create directory with read-only stream wrapper.');
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $this->assertFalse(@$file_system->mkdir($readonlydir, 0775, 0), 'Unable to create directory with read-only stream wrapper.');
     // Create a temporary directory for testing purposes
-    $this->assertTrue(drupal_mkdir($dir), 'Test directory created.');
+    $this->assertTrue($file_system->mkdir($dir), 'Test directory created.');
     // Test the rmdir() function by attempting to remove the directory.
-    $this->assertFalse(@drupal_rmdir($readonlydir), 'Unable to delete directory with read-only stream wrapper.');
+    $this->assertFalse(@$file_system->rmdir($readonlydir), 'Unable to delete directory with read-only stream wrapper.');
     // Remove the temporary directory.
-    drupal_rmdir($dir);
+    $file_system->rmdir($dir);
   }
 
 }
diff --git a/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php b/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php
index ff401e112ccf..d5ad4e891512 100644
--- a/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php
+++ b/core/tests/Drupal/KernelTests/Core/File/UrlRewritingTest.php
@@ -76,19 +76,21 @@ public function testPublicManagedFileURL() {
     $uri = $this->createUri();
     $url = file_create_url($uri);
     $public_directory_path = \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath();
-    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . drupal_basename($uri), $url, 'Correctly generated a CDN URL for a created file.');
+    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
+    $file_system = \Drupal::service('file_system');
+    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file_system->basename($uri), $url, 'Correctly generated a CDN URL for a created file.');
 
     // Test alteration of file URLs to use root-relative URLs.
     \Drupal::state()->set('file_test.hook_file_url_alter', 'root-relative');
     $uri = $this->createUri();
     $url = file_create_url($uri);
-    $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . drupal_basename($uri), $url, 'Correctly generated a root-relative URL for a created file.');
+    $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file_system->basename($uri), $url, 'Correctly generated a root-relative URL for a created file.');
 
     // Test alteration of file URLs to use a protocol-relative URLs.
     \Drupal::state()->set('file_test.hook_file_url_alter', 'protocol-relative');
     $uri = $this->createUri();
     $url = file_create_url($uri);
-    $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . drupal_basename($uri), $url, 'Correctly generated a protocol-relative URL for a created file.');
+    $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file_system->basename($uri), $url, 'Correctly generated a protocol-relative URL for a created file.');
   }
 
   /**
@@ -112,7 +114,7 @@ public function testRelativeFileURL() {
     $uri = $this->createUri();
     $url = file_create_url($uri);
     $public_directory_path = \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath();
-    $this->assertSame(base_path() . $public_directory_path . '/' . rawurlencode(drupal_basename($uri)), file_url_transform_relative($url));
+    $this->assertSame(base_path() . $public_directory_path . '/' . rawurlencode(\Drupal::service('file_system')->basename($uri)), file_url_transform_relative($url));
   }
 
 }
diff --git a/core/tests/Drupal/Tests/Core/Image/ImageTest.php b/core/tests/Drupal/Tests/Core/Image/ImageTest.php
index 30eca09f3b4a..0d0860c88264 100644
--- a/core/tests/Drupal/Tests/Core/Image/ImageTest.php
+++ b/core/tests/Drupal/Tests/Core/Image/ImageTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\Core\Image;
 
+use Drupal\Core\File\FileSystemInterface;
 use Drupal\Core\Image\Image;
 use Drupal\Core\ImageToolkit\ImageToolkitInterface;
 use Drupal\Tests\UnitTestCase;
@@ -210,9 +211,19 @@ public function testSave() {
       ->will($this->returnValue(TRUE));
 
     $image = $this->getMock('Drupal\Core\Image\Image', ['chmod'], [$toolkit, $this->image->getSource()]);
-    $image->expects($this->any())
-      ->method('chmod')
-      ->will($this->returnValue(TRUE));
+
+    $file_system = $this->prophesize(FileSystemInterface::class);
+    $file_system->chmod($this->image->getSource())
+      ->willReturn(TRUE);
+
+    $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
+      ->setMethods(['get'])
+      ->getMock();
+    $container->expects($this->once())
+      ->method('get')
+      ->with('file_system')
+      ->willReturn($file_system->reveal());
+    \Drupal::setContainer($container);
 
     $image->save();
   }
@@ -242,9 +253,19 @@ public function testChmodFails() {
       ->will($this->returnValue(TRUE));
 
     $image = $this->getMock('Drupal\Core\Image\Image', ['chmod'], [$toolkit, $this->image->getSource()]);
-    $image->expects($this->any())
-      ->method('chmod')
-      ->will($this->returnValue(FALSE));
+
+    $file_system = $this->prophesize(FileSystemInterface::class);
+    $file_system->chmod($this->image->getSource())
+      ->willReturn(FALSE);
+
+    $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
+      ->setMethods(['get'])
+      ->getMock();
+    $container->expects($this->once())
+      ->method('get')
+      ->with('file_system')
+      ->willReturn($file_system->reveal());
+    \Drupal::setContainer($container);
 
     $this->assertFalse($image->save());
   }
-- 
GitLab