IOHelper

Packagecraft.app.helpers
NamespaceCraft
Inheritanceclass IOHelper
Since1.0
Source Codecraft/app/helpers/IOHelper.php

Class IOHelper

Public Methods #

MethodDescriptionDefined By
changeGroup()Will attempt to change the group of the given file system path (*nix only)IOHelper
changeOwner()Will attempt to change the owner of the given file system path (*nix only)IOHelper
changePermissions()Will attempt to change the permission of the given file system path (*nix only).IOHelper
cleanFilename()Cleans a filename.IOHelper
cleanPath()Cleans a path.IOHelper
clearFile()Purges the contents of a file.IOHelper
clearFolder()Purges the contents of a folder while leaving the folder itself.IOHelper
copyFile()Will copy a file from one path to another and create folders if necessary.IOHelper
copyFolder()Will copy the contents of one folder to another.IOHelper
createFile()Will create a file on the file system at the given path and return a File object or false if we don't have write permissions.IOHelper
createFolder()Will create a folder on the file system at the given path and return a Folder object or false if we don't have write permissions.IOHelper
deleteFile()Deletes a file from the file system.IOHelper
deleteFolder()Deletes a folder from the file system.IOHelper
ensureFolderExists()Makes sure a folder exists. If it does not - creates one with write permissionsIOHelper
fileExists()Tests whether the given file path exists on the file system.IOHelper
folderExists()Tests whether the given folder path exists on the file system.IOHelper
getAllowedFileExtensions()Get a list of allowed file extensions.IOHelper
getDefaultFolderPermissions()Gets the default folder permissions from the config service.IOHelper
getExtension()Returns the file extension for the given path. If there is not one, then $default is returned instead.IOHelper
getFile()If the file exists on the file system will return a new File instance, otherwise, false.IOHelper
getFileContents()Will return the contents of the file as a string or an array if it exists and is readable, otherwise false.IOHelper
getFileKind()Return a file's kind by extension.IOHelper
getFileKindLabel()Returns the label of a given file kind.IOHelper
getFileKinds()Returns a list of file kinds.IOHelper
getFileMD5()Calculates the MD5 hash for a given file path or false if one could not be calculated or the file does not exist.IOHelper
getFileName()Will return the file name of the given path with or without the extension.IOHelper
getFileSize()Returns the file size in bytes for the given path or false if the file does not exist.IOHelper
getFiles()If the path exists on the file system, will return the paths of any files that are contained within it.IOHelper
getFolder()If the folder exists on the file system, will return a new Folder instance, otherwise, false.IOHelper
getFolderContents()Returns the contents of a folder as an array of file and folder paths, or false if the folder does not exist or is not readable.IOHelper
getFolderName()Will return the folder name of the given path either as the full path or only the single top level folder.IOHelper
getFolderSize()Returns the folder size in bytes for the given path or false if the folder does not exist.IOHelper
getFolders()If the path exists on the file system, will return the paths of any folders that are contained within it.IOHelper
getGroup()Returns group of current filesystem object (UNIX systems). Returned value depends upon $getName parameter value.IOHelper
getLastModifiedFiles()Returns the last $number of modified files from a given folder ordered by the last modified date descending.IOHelper
getLastTimeModified()Returns the last modified time for the given path in DateTime format or false if the file or folder does not exist.IOHelper
getMimeType()If the path points to a real file, we call FileHelper::getMimeType(), otherwise FileHelper::getMimeTypeByExtension()IOHelper
getMimeTypeByExtension()A wrapper for FileHelper::getMimeTypeByExtension().IOHelper
getOwner()Returns owner of current filesystem object (UNIX systems). Returned value depends upon $getName parameter value.IOHelper
getParentFolderPath()Returns a parent folder's path for a given path.IOHelper
getPermissions()Returns permissions of current filesystem object (UNIX systems).IOHelper
getRealPath()Returns the real filesystem path of the given path.IOHelper
getWritableFilePermissions()Gets the writable file permissions from the config service.IOHelper
getWritableFolderPermissions()Gets the writable folder permissions from the config service.IOHelper
handleError()Custom error handler used in IOHelper used for detecting if the file system supports exclusive locks when writing.IOHelper
isExtensionAllowed()Returns whether the extension is allowed.IOHelper
isFileEmpty()Will take a path, make sure the file exists and if the size of the file is 0 bytes, return true. Otherwise false.IOHelper
isFolderEmpty()Will take a path, make sure the folder exists and if the size of the folder is 0 bytes, return true. Otherwise false.IOHelper
isReadable()Tests whether the give filesystem path is readable.IOHelper
isWritable()Tests file and folder write-ability by attempting to create a temp file on the filesystem. PHP's is_writable has problems (especially on Windows). {@see https://bugs.php.net/bug.php?id=27609} and {@see https://bugs.php.net/bug.php?id=30931}.IOHelper
move()Moves a file from one location on disk to another.IOHelper
normalizePathSeparators()Will take a given path and normalize it to use single forward slashes for path separators. If it is a folder, it will append a trailing forward slash to the end of the path.IOHelper
rename()Renames a given file or folder to a new name.IOHelper
touch()Will set the access and modification times of the given file to the given time, or the current time if it is not supplied.IOHelper
writeToFile()Will write $contents to a file.IOHelper

Method Details #

changeGroup() #

public static function changeGroup($path, $group, $recursive = false, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (posix_getgrnam($group) == false xor (is_numeric($group) && posix_getgrgid($group) == false))
     {
          Craft::log('Tried to change the group of '.$path.', but the group name "'.$group.'" does not exist.', LogLevel::Error);
          return false;
     }

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          $success = $suppressErrors ? @chgrp($path, $group) : chgrp($path, $group);

          if ($success && static::folderExists($path, false, $suppressErrors) && $recursive)
          {
               $contents = static::getFolderContents($path, true, null, false, $suppressErrors);

               if ($contents)
               {
                    foreach ($contents as $path)
                    {
                         $path = static::normalizePathSeparators($path);

                         if ($suppressErrors ? !@chgrp($path, $group) : chgrp($path, $group))
                         {
                              $success = false;
                         }
                    }
               }
          }

          if (!$success)
          {
               Craft::log('Tried to change the group of '.$path.', but could not.', LogLevel::Error);
               return false;
          }

          return true;
     }
     else
     {
          Craft::log('Tried to change group of '.$path.', but that path does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path to change the group of.
$groupstringThe new group name.
$recursiveboolIf the path is a directory, whether to recursively change the group of the child files and folders.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if not, or the given path does not exist.

Will attempt to change the group of the given file system path (*nix only)

changeOwner() #

public static function changeOwner($path, $owner, $recursive = false, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (posix_getpwnam($owner) == false xor (is_numeric($owner) && posix_getpwuid($owner)== false))
     {
          Craft::log('Tried to change the owner of '.$path.', but the owner name "'.$owner.'" does not exist.', LogLevel::Error);
          return false;
     }

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          $success = $suppressErrors ? @chown($path, $owner) : chown($path, $owner);

          if ($success && static::folderExists($path, false, $suppressErrors) && $recursive)
          {
               $contents = static::getFolderContents($path, true, null, false, $suppressErrors);

               if ($contents)
               {
                    foreach ($contents as $path)
                    {
                         $path = static::normalizePathSeparators($path);

                         if ($suppressErrors ? !@chown($path, $owner) : chown($path, $owner))
                         {
                              $success = false;
                         }
                    }
               }
          }

          if (!$success)
          {
               Craft::log('Tried to change the own of '.$path.', but could not.', LogLevel::Error);
               return false;
          }

          return true;
     }
     else
     {
          Craft::log('Tried to change owner of '.$path.', but that path does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path to change the owner of.
$ownerstringThe new owner's name.
$recursiveboolIf the path is a folder, whether to change the owner of all of the folder's children.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if not or the given path does not exist.

Will attempt to change the owner of the given file system path (*nix only)

changePermissions() #

public static function changePermissions($path, $permissions, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          if ($suppressErrors ? @chmod($path, $permissions) : chmod($path, $permissions))
          {
               return true;
          }

          Craft::log('Tried to change the permissions of '.$path.', but could not.', LogLevel::Error);
     }
     else
     {
          Craft::log('Tried to change permissions of '.$path.', but that path does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path to change the permissions of.
$permissionsintThe new permissions.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if not or the path does not exist.

Will attempt to change the permission of the given file system path (*nix only).

cleanFilename() #

public static function cleanFilename($fileName, $onlyAscii = false, $separator = '-')
{
     $disallowedChars = array('—', '–', '&#8216;', '&#8217;', '&#8220;', '&#8221;', '&#8211;', '&#8212;', '+', '%', '^', '~', '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}');

     // Replace any control characters in the name with a space.
     $fileName = preg_replace( "#\x{00a0}#siu", ' ', $fileName );

     // Strip any characters not allowed.
     $fileName = str_replace($disallowedChars, '', strip_tags($fileName));

     if (!is_null($separator))
     {
          $fileName = preg_replace('/(\s|'.preg_quote($separator).')+/u', $separator, $fileName);
     }

     // Nuke any trailing or leading .-_
     $fileName = trim($fileName, '.-_');

     $fileName = ($onlyAscii) ? StringHelper::asciiString($fileName) : $fileName;

     return $fileName;
}
$fileNamestringThe filename to clean.
$onlyAsciiboolWhether to only allow ASCII characters in the filename.
$separatorstringThe separator to use for any whitespace. Defaults to '-'.
Returnsstring

The cleansed filename.

Cleans a filename.

cleanPath() #

public static function cleanPath($path, $onlyAscii = false, $separator = '-')
{
     $segments = explode('/', $path);

     foreach ($segments as &$segment)
     {
          $segment = self::cleanFilename($segment, $onlyAscii, $separator);
     }

     return implode('/', $segments);
}
$pathstringThe path to clean.
$onlyAsciiboolWhether to only allow ASCII characters in the path.
$separatorstringThe separator to use for any whitespace. Defaults to '-'.
Returnsstring

The cleansed path.

Cleans a path.

clearFile() #

public static function clearFile($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors))
     {
          if (static::isWritable($path, $suppressErrors))
          {
               static::writeToFile($path, '', false, $suppressErrors);
               return true;
          }
          else
          {
               Craft::log('Could not clear the contents of '.$path.' because the source file is not writable.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Could not clear the contents of '.$path.' because the source file does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the file to clear.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if the file was successfully cleared, 'false' if it wasn't, if the file is not writable or the file does not exist.

Purges the contents of a file.

clearFolder() #

public static function clearFolder($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          $folderContents = static::getFolderContents($path, true, null, true, $suppressErrors);

          if ($folderContents)
          {
               foreach ($folderContents as $item)
               {
                    $item = static::normalizePathSeparators($item);

                    if (static::fileExists($item, false, $suppressErrors))
                    {
                         static::deleteFile($item, $suppressErrors);
                    }
                    elseif (static::folderExists($item, false, $suppressErrors))
                    {
                         static::deleteFolder($item, $suppressErrors);
                    }
               }

               return true;
          }
          else
          {
               Craft::log('Tried to read the folder contents of '.$path.', but could not.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Could not clear the contents of '.$path.' because the source folder does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the folder to clear.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if is successfully purges the folder, 'false' if the folder does not exist.

Purges the contents of a folder while leaving the folder itself.

copyFile() #

public static function copyFile($path, $destination, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors))
     {
          $destFolder = static::getFolderName($destination, true, $suppressErrors);

          if (!static::folderExists($destFolder, false, $suppressErrors))
          {
               static::createFolder($destFolder, craft()->config->get('defaultFolderPermissions'), $suppressErrors);
          }

          if (static::isReadable($path, $suppressErrors))
          {
               if ($suppressErrors ? @copy($path, $destination) : copy($path, $destination))
               {
                    return true;
               }

               Craft::log('Tried to copy '.$path.' to '.$destination.', but could not.', LogLevel::Error);
          }
          else
          {
               Craft::log('Tried to copy '.$path.' to '.$destination.', but could not read the source file.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Tried to copy '.$path.' to '.$destination.', but the source file does not exist.', LogLevel::Error);
     }

     return false;

}
$pathstringThe source path of the file.
$destinationstringThe destination path to copy the file to.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if the copy was successful, 'false' if it was not, the source file is not readable or does not exist.

Will copy a file from one path to another and create folders if necessary.

copyFolder() #

public static function copyFolder($path, $destination, $validate = false, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);
     $destination = static::normalizePathSeparators($destination);

     if (static::folderExists($path, false, $suppressErrors))
     {
          $folderContents = static::getFolderContents($path, true, null, true, $suppressErrors);

          if ($folderContents)
          {
               foreach ($folderContents as $item)
               {
                    $itemDest = IOHelper::normalizePathSeparators($destination.'/'.str_replace($path, '', $item));
                    $destFolder = static::getFolderName($itemDest, true, $suppressErrors);

                    if (!static::folderExists($destFolder, false, $suppressErrors))
                    {
                         static::createFolder($destFolder, craft()->config->get('defaultFolderPermissions'), $suppressErrors);
                    }

                    if (static::fileExists($item, false, $suppressErrors))
                    {
                         $result = $suppressErrors ? @copy($item, $itemDest) : copy($item, $itemDest);

                         if (!$result)
                         {
                              Craft::log('Could not copy file from '.$item.' to '.$itemDest.'.', LogLevel::Error);
                         }
                    }
                    elseif (static::folderExists($item, false, $suppressErrors))
                    {
                         if (!static::createFolder($itemDest, $suppressErrors))
                         {
                              Craft::log('Could not create destination folder '.$itemDest, LogLevel::Error);
                         }
                    }
               }
          }

          if ($validate)
          {
               if (static::getFolderSize($path, $suppressErrors) !== static::getFolderSize($destination, $suppressErrors))
               {
                    return false;
               }
          }

          return true;
     }
     else
     {
          Craft::log('Cannot copy folder '.$path.' to '.$destination.' because the source path does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe source path to copy.
$destinationstringThe destination path to copy to.
$validateboolWhether to compare the size of the folders after the copy is complete.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if the copy was successful, 'false' if it was not, or $validate is true and the size of the folders do not match after the copy.

Will copy the contents of one folder to another.

createFile() #

public static function createFile($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (!static::fileExists($path, false, $suppressErrors))
     {
          if (($handle = $suppressErrors ? @fopen($path, 'w') : fopen($path, 'w')) === false)
          {
               Craft::log('Tried to create a file at '.$path.', but could not.', LogLevel::Error);
               return false;
          }

          @fclose($handle);
          return new File($path);
     }

     return false;
}
$pathstringThe path of the file to create.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
ReturnsFile / bool

The newly created file as a File object or false if we don't have write permissions.

Will create a file on the file system at the given path and return a File object or false if we don't have write permissions.

createFolder() #

public static function createFolder($path, $permissions = null, $suppressErrors = false)
{
     if ($permissions == null)
     {
          $permissions = craft()->config->get('defaultFolderPermissions');
     }

     $path = static::normalizePathSeparators($path);

     if (!static::folderExists($path, false, $suppressErrors))
     {
          $oldumask = $suppressErrors ? @umask(0) : umask(0);

          if ($suppressErrors ? !@mkdir($path, $permissions, true) : !mkdir($path, $permissions, true))
          {
               Craft::log('Tried to create a folder at '.$path.', but could not.', LogLevel::Error);
               return false;
          }

          // Because setting permission with mkdir is a crapshoot.
          $suppressErrors ? @chmod($path, $permissions) : chmod($path, $permissions);
          $suppressErrors ? @umask($oldumask) : umask($oldumask);
          return new Folder($path);
     }

     Craft::log('Tried to create a folder at '.$path.', but the folder already exists.', LogLevel::Warning);
     return false;
}
$pathstringThe path of the file to create.
$permissionsintThe permissions to set the folder to.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
ReturnsFolder / bool

The newly created folder as a Folder object or false if we don't have write permissions.

Will create a folder on the file system at the given path and return a Folder object or false if we don't have write permissions.

deleteFile() #

public static function deleteFile($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors))
     {
          if (static::isWritable($path, $suppressErrors))
          {
               if ($suppressErrors ? @unlink($path) : unlink($path))
               {
                    return true;
               }
               else
               {
                    Craft::log('Could not delete the file '.$path.'.', LogLevel::Error);
               }
          }
          else
          {
               Craft::log('Could not delete the file '.$path.' because it is not writable.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Could not delete the file '.$path.' because the file does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the file to delete.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if it cannot be deleted, it does not exist or it is not writable.

Deletes a file from the file system.

deleteFolder() #

public static function deleteFolder($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          if (static::isWritable($path, $suppressErrors))
          {
               // Empty the folder contents first.
               static::clearFolder($path, $suppressErrors);

               // Delete the folder.
               if ($suppressErrors ? @rmdir($path) : rmdir($path))
               {
                    return true;
               }
               else
               {
                    Craft::log('Could not delete the folder '.$path.'.', LogLevel::Error);
               }
          }
          else
          {
               Craft::log('Could not delete the folder '.$path.' because it is not writable.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Could not delete the folder '.$path.' because the folder does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the folder to delete.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if it cannot be deleted, it does not exist or it is not writable.

Deletes a folder from the file system.

ensureFolderExists() #

public static function ensureFolderExists($folderPath, $suppressErrors = false)
{
     if (!IOHelper::folderExists($folderPath, false, $suppressErrors))
     {
          IOHelper::createFolder($folderPath, craft()->config->get('defaultFolderPermissions'), $suppressErrors);
     }
}
$folderPathstringThe path to the folder.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).

Makes sure a folder exists. If it does not - creates one with write permissions

fileExists() #

public static function fileExists($path, $caseInsensitive = false, $suppressErrors = false)
{
     $resolvedPath = static::getRealPath($path, $suppressErrors);

     if ($resolvedPath)
     {
          if ($suppressErrors ? @is_file($resolvedPath) : is_file($resolvedPath))
          {
               return $resolvedPath;
          }
     }
     else if ($caseInsensitive)
     {
          $folder = static::getFolderName($path, true, $suppressErrors);
          $files = static::getFolderContents($folder, false, null, false, $suppressErrors);
          $lcaseFileName = StringHelper::toLowerCase($path);

          if (is_array($files) && count($files) > 0)
          {
               foreach ($files as $file)
               {
                    $file = static::normalizePathSeparators($file);

                    if ($suppressErrors ? @is_file($file) : is_file($file))
                    {
                         if (StringHelper::toLowerCase($file) === $lcaseFileName)
                         {
                              return $file;
                         }
                    }
               }
          }
     }

     return false;
}
$pathstringThe path to test.
$caseInsensitiveboolWhether to perform a case insensitive check or not.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring

The resolved path of the file if it exists.

Tests whether the given file path exists on the file system.

folderExists() #

public static function folderExists($path, $caseInsensitive = false, $suppressErrors = false)
{
     $path = static::getRealPath($path, $suppressErrors);

     if ($path)
     {
          if ($suppressErrors ? @is_dir($path) : is_dir($path))
          {
               return $path;
          }

          if ($caseInsensitive)
          {
               return StringHelper::toLowerCase(static::getFolderName($path, true, $suppressErrors)) === StringHelper::toLowerCase($path);
          }
     }

     return false;
}
$pathstringThe path to test.
$caseInsensitiveboolWhether to perform a case insensitive check or not.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if the folder exists, otherwise 'false'.

Tests whether the given folder path exists on the file system.

getAllowedFileExtensions() #

public static function getAllowedFileExtensions()
{
     $allowedFileExtensions = ArrayHelper::stringToArray(craft()->config->get('allowedFileExtensions'));

     if (($extraExtensions = craft()->config->get('extraAllowedFileExtensions')) !== '')
     {
          $extraExtensions = ArrayHelper::stringToArray($extraExtensions);
          $allowedFileExtensions = array_merge($allowedFileExtensions, $extraExtensions);
     }

     return  $allowedFileExtensions;
}
Returnsarray

Get a list of allowed file extensions.

getDefaultFolderPermissions() #

public static function getDefaultFolderPermissions()
{
     return craft()->config->get('defaultFolderPermissions');
}
Returnsmixed

Deprecated in 2.2. Use craft()->config->get('defaultFolderPermissions') instead.

Gets the default folder permissions from the config service.

getExtension() #

public static function getExtension($path, $default = null, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);
     $extension = $suppressErrors ? @pathinfo($path, PATHINFO_EXTENSION) : pathinfo($path, PATHINFO_EXTENSION);

     if ($extension)
     {
          return $extension;
     }
     else
     {
          return $default;
     }
}
$pathstringThe path to test.
$defaultnull / stringIf the file has no extension, this one will be returned by default.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring

The file extension.

Returns the file extension for the given path. If there is not one, then $default is returned instead.

getFile() #

public static function getFile($path, $suppressErrors = false)
{
     if (static::fileExists($path, false, $suppressErrors))
     {
          return new File($path);
     }

     return false;
}
$pathstringThe path to the file.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
ReturnsFile / bool

If the file exists on the file system will return a new File instance, otherwise, false.

getFileContents() #

public static function getFileContents($path, $array = false, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) && static::isReadable($path, $suppressErrors))
     {
          if ($array)
          {
               if (($contents = $suppressErrors ? @file($path) : file($path)) !== false)
               {
                    return $contents;
               }
          }
          else
          {
               if (($contents = $suppressErrors ? @file_get_contents($path) : file_get_contents($path)) !== false)
               {
                    return $contents;
               }
          }

          Craft::log('Tried to read the file contents at '.$path.' and could not.', LogLevel::Error);
          return false;
     }

     Craft::log('Tried to read the file contents at '.$path.', but either the file does not exist or is it not readable.', LogLevel::Error);
     return false;
}
$pathstringThe path of the file.
$arrayboolWhether to return the contents of the file as an array or not.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool / string / array

The contents of the file as a string, an array, or false if the file does not exist or is not readable.

Will return the contents of the file as a string or an array if it exists and is readable, otherwise false.

getFileKind() #

public static function getFileKind($extension)
{
     $extension = StringHelper::toLowerCase($extension);
     $fileKinds = static::getFileKinds();

     foreach ($fileKinds as $kind => $info)
     {
          if (in_array($extension, $info['extensions']))
          {
               return $kind;
          }
     }

     return 'unknown';
}
$extensionstring
Returnsint / string

Return a file's kind by extension.

getFileKindLabel() #

public static function getFileKindLabel($kind)
{
     self::_buildFileKinds();

     if (isset(self::$_fileKinds[$kind]['label']))
     {
          return self::$_fileKinds[$kind]['label'];
     }
     else
     {
          return null;
     }
}
$kindstring
Returnsarray

Returns the label of a given file kind.

getFileKinds() #

public static function getFileKinds()
{
     self::_buildFileKinds();

     return self::$_fileKinds;
}
Returnsarray

Returns a list of file kinds.

getFileMD5() #

public static function getFileMD5($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) && static::isReadable($path, $suppressErrors))
     {
          return $suppressErrors ? @md5_file($path) : md5_file($path);
     }
     else
     {
          Craft::log('Could not calculate the MD5 for the file '.$path.' because the file does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the file to calculate.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool / string

The MD5 hash or false if it does not exist, isn't readable or could not be calculated.

Calculates the MD5 hash for a given file path or false if one could not be calculated or the file does not exist.

getFileName() #

public static function getFileName($path, $includeExtension = true, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if ($includeExtension)
     {
          return $suppressErrors ? @pathinfo($path, PATHINFO_BASENAME) : pathinfo($path, PATHINFO_BASENAME);
     }
     else
     {
          return $suppressErrors ? @pathinfo($path, PATHINFO_FILENAME) : pathinfo($path, PATHINFO_FILENAME);
     }
}
$pathstringThe path to test.
$includeExtensionboolWhether to include the extension in the file name.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring

The file name with or without the extension.

Will return the file name of the given path with or without the extension.

getFileSize() #

public static function getFileSize($path, $suppressErrors = false)
{
     clearstatcache();

     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors))
     {
          return sprintf("%u", $suppressErrors ? @filesize($path) : filesize($path));
     }

     return false;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool / string

The file size in bytes or false if the file does not exist.

Returns the file size in bytes for the given path or false if the file does not exist.

getFiles() #

public static function getFiles($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          $glob = $suppressErrors ? @glob($path.'*') : glob($path.'*');
          $files = array();

          foreach ($glob as $file)
          {
               if ($suppressErrors ? @is_file($file) : is_file($file))
               {
                    $files[] = static::normalizePathSeparators($file);
               }
          }

          return $files;
     }

     return false;
}
$pathstringThe folder path to check
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsarray / bool

If the path exists on the file system, will return the paths of any files that are contained within it.

getFolder() #

public static function getFolder($path, $suppressErrors = false)
{
     if (static::folderExists($path, false, $suppressErrors))
     {
          return new Folder($path);
     }

     return false;
}
$pathstringThe path to the folder.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
ReturnsFolder / bool

If the folder exists on the file system, will return a new Folder instance, otherwise, false.

getFolderContents() #

public static function getFolderContents($path, $recursive = true, $filter = null, $includeHiddenFiles = false, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          if (static::isReadable($path, $suppressErrors))
          {
               if (($contents = static::_folderContents($path, $recursive, $filter, $includeHiddenFiles, $suppressErrors)) !== false)
               {
                    return $contents;
               }

               return false;
          }

          Craft::log('Tried to read the folder contents at '.$path.', but it is not readable.');
          return false;
     }

     Craft::log('Tried to read the folder contents at '.$path.', but it does not exist.');
     return false;
}
$pathstringThe path to test.
$recursiveboolWhether to do a recursive folder search.
$filterboolThe filter to use when performing the search.
$includeHiddenFilesboolWhether to include hidden files (that start with a .) in the results.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsarray / bool

An array of file and folder paths, or false if the folder does not exist or is not readable.

Returns the contents of a folder as an array of file and folder paths, or false if the folder does not exist or is not readable.

getFolderName() #

public static function getFolderName($path, $fullPath = true, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if ($fullPath)
     {
          $folder = static::normalizePathSeparators($suppressErrors ? @pathinfo($path, PATHINFO_DIRNAME) : pathinfo($path, PATHINFO_DIRNAME));

          // normalizePathSeparators() only enforces the trailing slash for known directories so let's be sure
          // that it'll be there.
          return rtrim($folder, '/').'/';
     }
     else
     {
          if ($suppressErrors ? !@is_dir($path) : !is_dir($path))
          {
               // Chop off the file
               $path = $suppressErrors ? @pathinfo($path, PATHINFO_DIRNAME) : pathinfo($path, PATHINFO_DIRNAME);
          }

          return $suppressErrors ? @pathinfo($path, PATHINFO_BASENAME) : pathinfo($path, PATHINFO_BASENAME);
     }
}
$pathstringThe path to test.
$fullPathboolWhether to include the full path in the return results or the top level folder only.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring

The folder name.

Will return the folder name of the given path either as the full path or only the single top level folder.

getFolderSize() #

public static function getFolderSize($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          return sprintf("%u", static::_folderSize($path, $suppressErrors));
     }

     return false;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool / string

The folder size in bytes or false if the folder does not exist.

Returns the folder size in bytes for the given path or false if the folder does not exist.

getFolders() #

public static function getFolders($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          $folders = $suppressErrors ? @glob($path.'*', GLOB_ONLYDIR) : glob($path.'*', GLOB_ONLYDIR);

          if ($folders)
          {
               foreach ($folders as $key => $folder)
               {
                    $folders[$key] = static::normalizePathSeparators($folder);
               }

               return $folders;
          }
     }

     return false;
}
$pathstringThe folder path to check
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsarray / bool

If the path exists on the file system, will return the paths of any folders that are contained within it.

getGroup() #

public static function getGroup($path, $getName = true, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          $group = $suppressErrors ? @filegroup($path) : filegroup($path);
     }
     else
     {
          $group =  false;
     }

     if (is_int($group) && function_exists('posix_getgrgid') && $getName == true)
     {
          $group = posix_getgrgid($group);
          $group = $group['name'];
     }

     return $group;
}
$pathstringThe path to check.
$getNameboolDefaults to 'true', meaning that group name instead of ID should be returned.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsmixed

Group name, or ID if $getName set to 'false' or false if the file or folder does not exist.

Returns group of current filesystem object (UNIX systems). Returned value depends upon $getName parameter value.

getLastModifiedFiles() #

public static function getLastModifiedFiles($folder, $number = null, $suppressErrors = false)
{
     $fileResults = array();

     $files = static::getFiles($folder, $suppressErrors);

     foreach ($files as $file)
     {
          $lastModifiedTime = IOHelper::getLastTimeModified($file, $suppressErrors);
          $fileResults[$lastModifiedTime->getTimestamp()] = $file;
     }

     krsort($fileResults);

     if ($number !== null)
     {
          $fileResults = array_slice($fileResults, 0, $number, true);
     }

     return $fileResults;
}
$folderstringThe folder to get the files from.
$numberintThe number of files to return. If null is given, all files will be returned.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsarray

Returns the last $number of modified files from a given folder ordered by the last modified date descending.

getLastTimeModified() #

public static function getLastTimeModified($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          $timeStamp = $suppressErrors ? @filemtime($path) : filemtime($path);
          return new DateTime('@'.$timeStamp);
     }

     return false;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsint / bool

The last modified timestamp or false if the file or folder does not exist.

Returns the last modified time for the given path in DateTime format or false if the file or folder does not exist.

getMimeType() #

public static function getMimeType($path)
{
     if (@file_exists($path))
     {
          return FileHelper::getMimeType($path);
     }
     else
     {
          return FileHelper::getMimeTypeByExtension($path);
     }
}
$pathstringThe path to test.
Returnsstring

The mime type.

If the path points to a real file, we call FileHelper::getMimeType(), otherwise FileHelper::getMimeTypeByExtension()

getMimeTypeByExtension() #

public static function getMimeTypeByExtension($path)
{
     return FileHelper::getMimeTypeByExtension($path);
}
$pathstringThe path to test.
Returnsstring

The mime type.

A wrapper for FileHelper::getMimeTypeByExtension().

getOwner() #

public static function getOwner($path, $getName = true, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          $owner = $suppressErrors ? @fileowner($path) : fileowner($path);
     }
     else
     {
          $owner =  false;
     }

     if (is_int($owner) && function_exists('posix_getpwuid') && $getName == true)
     {
          $owner = posix_getpwuid($owner);
          $owner = $owner['name'];
     }

     return $owner;
}
$pathstringThe path to check.
$getNameboolDefaults to 'true', meaning that owner name instead of ID should be returned.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsmixed

Owner name, or ID if $getName set to 'false' or false if the file or folder does not exist.

Returns owner of current filesystem object (UNIX systems). Returned value depends upon $getName parameter value.

getParentFolderPath() #

public static function getParentFolderPath($fullPath)
{
     $fullPath = static::normalizePathSeparators($fullPath);

     // Drop the trailing slash and split it by slash
     $parts = explode("/", rtrim($fullPath, "/"));

     // Drop the last part and return the part leading up to it
     array_pop($parts);

     if (empty($parts))
     {
          return '';
     }

     return join("/", $parts).'/';
}
$fullPathstringThe path to get the parent folder path for.
Returnsstring

Returns a parent folder's path for a given path.

getPermissions() #

public static function getPermissions($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          return mb_substr(sprintf('%o', $suppressErrors ? @fileperms($path) : fileperms($path)), -4);
     }

     return false;
}
$pathstringThe path to check
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring

Filesystem object permissions in octal format (i.e. '0755'), false if the file or folder doesn't exist

Returns permissions of current filesystem object (UNIX systems).

getRealPath() #

public static function getRealPath($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);
     $path = $suppressErrors ? @realpath($path) : realpath($path);

     // realpath() should just return false if the file doesn't exist, but seeing one case where
     // it's returning an empty string instead
     if (!$path)
     {
          return false;
     }

     if ($suppressErrors ? @is_dir($path) : is_dir($path))
     {
          $path = $path.'/';
     }

     // Normalize again, because realpath probably screwed things up again.
     return static::normalizePathSeparators($path);
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsstring / false

The real file or folder path, or falseif the file doesn’t exist.

Returns the real filesystem path of the given path.

getWritableFilePermissions() #

public static function getWritableFilePermissions()
{
     return craft()->config->get('defaultFilePermissions');
}
Returnsmixed

Deprecated in 2.2. Use craft()->config->get('defaultFilePermissions') instead.

Gets the writable file permissions from the config service.

getWritableFolderPermissions() #

public static function getWritableFolderPermissions()
{
     return craft()->config->get('defaultFolderPermissions');
}
Returnsmixed

Deprecated in 2.2. Use craft()->config->get('defaultFolderPermissions') instead.

Gets the writable folder permissions from the config service.

handleError() #

public function handleError($errNo, $errStr, $errFile, $errLine, array $errContext)
{
     // The error was suppressed with the @-operator
     if (0 === error_reporting())
     {
          return false;
     }

     $message = 'ErrNo: '.$errNo.': '.$errStr.' in file: '.$errFile.' on line: '.$errLine.'.';

     throw new ErrorException($message, 0);
}
$errNo$errNo
$errStr$errStr
$errFile$errFile
$errLine$errLine
$errContextarray
Returnsbool

Custom error handler used in IOHelper used for detecting if the file system supports exclusive locks when writing.

isExtensionAllowed() #

public static function isExtensionAllowed($extension)
{
     static $extensions = null;

     if (is_null($extensions))
     {
          $extensions = array_map('mb_strtolower', static::getAllowedFileExtensions());
     }

     return in_array(mb_strtolower($extension), $extensions);
}
$extension$extension
Returnsbool

Returns whether the extension is allowed.

isFileEmpty() #

public static function isFileEmpty($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if ((static::fileExists($path, false, $suppressErrors) && static::getFileSize($path, $suppressErrors) == 0))
     {
          return true;
     }

     return false;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

Whether the file is empty or not.

Will take a path, make sure the file exists and if the size of the file is 0 bytes, return true. Otherwise false.

isFolderEmpty() #

public static function isFolderEmpty($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if ((static::folderExists($path, false, $suppressErrors) && static::getFolderSize($path, $suppressErrors) == 0))
     {
          return true;
     }

     return false;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

Whether the folder is empty or not.

Will take a path, make sure the folder exists and if the size of the folder is 0 bytes, return true. Otherwise false.

isReadable() #

public static function isReadable($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);
     return $suppressErrors ? @is_readable($path) : is_readable($path);
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if filesystem path is readable, otherwise 'false'.

Tests whether the give filesystem path is readable.

isWritable() #

public static function isWritable($path, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::folderExists($path, false, $suppressErrors))
     {
          return static::isWritable($path.uniqid(mt_rand()).'.tmp', $suppressErrors);
     }

     // Check tmp file for read/write capabilities
     $rm = static::fileExists($path, false, $suppressErrors);
     $f = @fopen($path, 'a');

     if ($f === false)
     {
          return false;
     }

     @fclose($f);

     if (!$rm)
     {
          @unlink($path);
     }

     return true;
}
$pathstringThe path to test.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if filesystem object is writable, otherwise 'false'.

Tests file and folder write-ability by attempting to create a temp file on the filesystem. PHP's is_writable has problems (especially on Windows). {@see https://bugs.php.net/bug.php?id=27609} and {@see https://bugs.php.net/bug.php?id=30931}.

move() #

public static function move($path, $newPath, $suppressErrors = false)
{
     return static::rename($path, $newPath, $suppressErrors);
}
$pathstringThe original path of the file/folder to move.
$newPathstringThe new path the file/folder should be moved to.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if the file was successfully moved, 'false', otherwise.

Moves a file from one location on disk to another.

normalizePathSeparators() #

public static function normalizePathSeparators($path)
{
     $isUNC = false;

     // Special case for normalizing UNC network share paths.
     if (isset($path[0]) && isset($path[1]))
     {
          if (($path[0] == '\\' && $path[1] == '\\') ||($path[0] == '/' && $path[1] == '/') )
          {
               $path = mb_substr($path, 2);
               $path = str_replace('\\', '/', $path);

               // Add the share back in
               $path = '\\\\'.$path;
               $isUNC = true;
          }
     }

     if (!$isUNC)
     {
          // Make everything forward slash.
          $path = str_replace('\\', '/', $path);
     }

     // Replace any double forwards with singles.
     $path = str_replace('//', '/', $path);

     // Check if the path is just a slash.  If the server has openbase_dir restrictions in place calling is_dir on it
     // will complain.
     if ($path !== '/')
     {
          // Use is_dir here to prevent an endless recursive loop.
          // Always suppress errors here because of openbase_dir, too.
          if (@is_dir($path))
          {
               $path = rtrim($path, '\/').'/';
          }
     }

     return $path;
}
$pathstringThe path to normalize.
Returnsstring

The normalized path.

Will take a given path and normalize it to use single forward slashes for path separators. If it is a folder, it will append a trailing forward slash to the end of the path.

rename() #

public static function rename($path, $newName, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (static::fileExists($path, false, $suppressErrors) || static::folderExists($path, false, $suppressErrors))
     {
          // If we're renaming a file and there is no extension on the new name, default to the old extension
          if (static::fileExists($path, false, $suppressErrors) && !static::getExtension($newName, null, $suppressErrors))
          {
               $newName .= '.'.static::getExtension($path, null, $suppressErrors);
          }

          if (static::isWritable($path, $suppressErrors))
          {
               if ($suppressErrors ? @rename($path, $newName) : rename($path, $newName))
               {
                    return true;
               }
               else
               {
                    Craft::log('Could not rename '.$path.' to '.$newName.'.', LogLevel::Error);
               }
          }
          else
          {
               Craft::log('Could not rename '.$path.' to '.$newName.' because the source file or folder is not writable.', LogLevel::Error);
          }
     }
     else
     {
          Craft::log('Could not rename '.$path.' to '.$newName.' because the source file or folder does not exist.', LogLevel::Error);
     }

     return false;
}
$pathstringThe original path of the file or folder.
$newNamestringThe new name of the file or folder.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' if successful, 'false' if not or the source file or folder does not exist.

Renames a given file or folder to a new name.

touch() #

public static function touch($fileName, $time = null, $suppressErrors = false)
{
     if (!$time)
     {
          $time = time();
     }

     if ($suppressErrors ? @touch($fileName, $time) : touch($fileName, $time))
     {
          return true;
     }

     return false;
}
$fileNamestringThe path to the file/folder to touch.
$timenullThe time to set on the file/folder. If none is provided, will default to the current time.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

Will set the access and modification times of the given file to the given time, or the current time if it is not supplied.

writeToFile() #

public static function writeToFile($path, $contents, $autoCreate = true, $append = false, $noFileLock = null, $suppressErrors = false)
{
     $path = static::normalizePathSeparators($path);

     if (!static::fileExists($path, false, $suppressErrors) && $autoCreate)
     {
          $folderName = static::getFolderName($path, true, $suppressErrors);

          if (!static::folderExists($folderName, false, $suppressErrors))
          {
               if (!static::createFolder($folderName, $suppressErrors))
               {
                    return false;
               }
          }

          if ((!static::createFile($path, $suppressErrors)) !== false)
          {
               return false;
          }
     }

     if (static::isWritable($path, $suppressErrors))
     {
          // Let's try to use our auto-magic detection.
          if (craft()->config->get('useWriteFileLock') === 'auto')
          {
               // We haven't cached file lock information yet and this is not a noFileLock request.
               if (($useFileLock = craft()->cache->get('useWriteFileLock')) === false && !$noFileLock)
               {
                    // For file systems that don't support file locking... LOOKING AT YOU NFS!!!
                    set_error_handler(array(new IOHelper(), 'handleError'));

                    try
                    {
                         Craft::log('Trying to write to file at '.$path.' using LOCK_EX.', LogLevel::Info);
                         if (static::_writeToFile($path, $contents, true, $append, $suppressErrors))
                         {
                              // Restore quickly.
                              restore_error_handler();

                              // Cache the file lock info to use LOCK_EX for 2 months.
                              Craft::log('Successfully wrote to file at '.$path.' using LOCK_EX. Saving in cache.', LogLevel::Info);
                              craft()->cache->set('useWriteFileLock', 'yes', 5184000);
                              return true;
                         }
                         else
                         {
                              // Try again without the lock flag.
                              Craft::log('Trying to write to file at '.$path.' without LOCK_EX.', LogLevel::Info);
                              if (static::_writeToFile($path, $contents, false, $append, $suppressErrors))
                              {
                                   // Cache the file lock info to not use LOCK_EX for 2 months.
                                   Craft::log('Successfully wrote to file at '.$path.' without LOCK_EX. Saving in cache.', LogLevel::Info);
                                   craft()->cache->set('useWriteFileLock', 'no', 5184000);
                                   return true;
                              }
                         }
                    }
                    catch (ErrorException $e)
                    {
                         // Restore here before we attempt to write again.
                         restore_error_handler();

                         // Try again without the lock flag.
                         Craft::log('Trying to write to file at '.$path.' without LOCK_EX.', LogLevel::Info);
                         if (static::_writeToFile($path, $contents, false, $append, $suppressErrors))
                         {
                              // Cache the file lock info to not use LOCK_EX for 2 months.
                              Craft::log('Successfully wrote to file at '.$path.' without LOCK_EX. Saving in cache.', LogLevel::Info);
                              craft()->cache->set('useWriteFileLock', 'no', 5184000);
                              return true;
                         }
                    }

                    // Make sure we're really restored
                    restore_error_handler();
               }
               else
               {
                    // If cache says use LOCK_X and this is not a noFileLock request.
                    if ($useFileLock == 'yes' && !$noFileLock)
                    {
                         // Write with LOCK_EX
                         if (static::_writeToFile($path, $contents, true, $append, $suppressErrors))
                         {
                              return true;
                         }
                    }
                    else
                    {
                         // Write without LOCK_EX
                         if (static::_writeToFile($path, $contents, false, $append, $suppressErrors))
                         {
                              return true;
                         }
                         else
                         {
                              Craft::log('Tried to write to file at '.$path.' and could not.', LogLevel::Error);
                              return false;
                         }
                    }

               }
          }
          // We were explicitly told not to use LOCK_EX
          else if (craft()->config->get('useWriteFileLock') === false)
          {
               if (static::_writeToFile($path, $contents, false, $append, $suppressErrors))
               {
                    return true;
               }
               else
               {
                    Craft::log('Tried to write to file at '.$path.' with no LOCK_EX and could not.', LogLevel::Error);
                    return false;
               }
          }
          // Not 'auto', not false, so default to using LOCK_EX
          else
          {
               if (static::_writeToFile($path, $contents, true, $append, $suppressErrors))
               {
                    return true;
               }
               else
               {
                    Craft::log('Tried to write to file at '.$path.' with LOCK_EX and could not.', LogLevel::Error);
                    return false;
               }
          }
     }
     else
     {
          Craft::log('Tried to write to file at '.$path.', but the file is not writable.', LogLevel::Error);
     }

     return false;
}
$pathstringThe path of the file to write to.
$contentsstringThe contents to be written to the file.
$autoCreateboolWhether or not to auto-create the file if it does not exist.
$appendboolIf true, will append the data to the contents of the file, otherwise it will overwrite the contents.
$noFileLockbool / nullWhether to use file locking when writing to the file.
$suppressErrorsboolWhether to suppress any PHP Notices/Warnings/Errors (usually permissions related).
Returnsbool

'true' upon successful writing to the file, otherwise false.

Will write $contents to a file.