CRM_Utils_File
in package
class to provide simple static functions for file objects
Table of Contents
Constants
- HASH_REMOVAL_PATTERN = '/_[a-f0-9]{32}\./'
- Used to remove md5 hash that was injected into uploaded file names.
Methods
- absoluteDirectory() : string
- addTrailingSlash() : string
- Appends a slash to the end of a string if it doesn't already end with one
- baseFilePath() : mixed
- (Deprecated) Create the file-path from which all other internal paths are computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
- cleanDir() : mixed
- Delete a directory given a path name, delete children directories and files if needed
- cleanFileName() : mixed
- Remove 32 bit md5 hash prepended to the file suffix.
- concat() : string
- Concatenate several files.
- copyDir() : mixed
- createDir() : bool|null
- Create a directory given a path name, creates parent directories if needed
- createFakeFile() : string
- Save a fake file somewhere
- duplicate() : mixed
- Copies a file
- findFiles() : mixed
- Search directory tree for files which match a glob pattern.
- formatFile() : mixed
- Format file.
- getAcceptableExtensionsForMimeType() : array<string|int, mixed>
- Get the extensions that this MimeTpe is for
- getExtensionFromPath() : string
- Get the extension of a file based on its path
- getFilesByExtension() : array<string|int, mixed>
- Get files for the extension.
- getFileURL() : string
- Return formatted file URL, like for image file return image url with image icon
- getIconFromMimeType() : string
- Get file icon class for specific MIME Type
- getImageURL() : string
- Return formatted image icon
- getMaxFileSize() : int
- Get the maximum file size permitted for upload.
- isAbsolute() : bool
- Determine if a path is absolute.
- isAscii() : bool
- Given a file name, determine if the file contents make it an ascii file
- isChildPath() : bool
- Determine if $child is a sub-directory of $parent
- isDir() : bool|null
- Wrapper for is_dir() to avoid flooding logs when open_basedir is used.
- isExtensionSafe() : bool
- isIncludable() : bool
- Determine whether a given file is listed in the PHP include path.
- isValidFileName() : bool
- Is the filename a safe and valid filename passed in from URL
- makeFileName() : string
- Make a valid file name.
- makeFilenameWithUnicode() : string
- CRM_Utils_String::munge() doesn't handle unicode and needs to be able to generate valid database tablenames so will sometimes generate a random string. Here what we want is a human-sensible filename that might contain unicode.
- relativize() : string
- Make a file path relative to some base dir.
- replaceDir() : bool
- Move $fromDir to $toDir, replacing/deleting any pre-existing content.
- resizeImage() : string
- Resize an image.
- restrictAccess() : mixed
- Restrict access to a given directory (by planting there a restrictive .htaccess file)
- restrictBrowsing() : mixed
- Restrict remote users from browsing the given directory.
- runSqlQuery() : mixed
- Runs an SQL query.
- sourceSQLFile() : mixed
- stripComments() : string
- Strips comment from a possibly multiline SQL string
- tempdir() : mixed
- Create a path to a temporary directory which can endure for multiple requests.
- tempnam() : mixed
- Create a path to a temporary file which can endure for multiple requests.
- toUtf8() : bool
- Given a file name, recode it (in place!) to UTF-8
- findPathDepth() : int
- Determine the absolute depth of a path expression.
- try_unlink() : mixed
- Helper function to avoid repetition in cleanDir: execute unlink and produce a warning on failure.
Constants
HASH_REMOVAL_PATTERN
Used to remove md5 hash that was injected into uploaded file names.
public
mixed
HASH_REMOVAL_PATTERN
= '/_[a-f0-9]{32}\./'
Methods
absoluteDirectory()
public
static absoluteDirectory(mixed $directory, string $basePath) : string
Parameters
- $directory : mixed
- $basePath : string
-
The base path when evaluating relative paths. Should include trailing slash.
Return values
stringaddTrailingSlash()
Appends a slash to the end of a string if it doesn't already end with one
public
static addTrailingSlash(string $path[, string $slash = NULL ]) : string
Parameters
- $path : string
- $slash : string = NULL
Return values
stringbaseFilePath()
(Deprecated) Create the file-path from which all other internal paths are computed. This implementation determines it as `dirname(CIVICRM_TEMPLATE_COMPILEDIR)`.
public
static baseFilePath() : mixed
This approach is problematic - e.g. it prevents one from authentically splitting the CIVICRM_TEMPLATE_COMPILEDIR away from other dirs. The implementation is preserved for backwards compatibility (and should only be called by CMS-adapters and by Civi\Core\Paths).
Do not use it for new path construction logic. Instead, use Civi::paths().
Tags
cleanDir()
Delete a directory given a path name, delete children directories and files if needed
public
static cleanDir(string $target[, bool $rmdir = TRUE ][, bool $verbose = TRUE ]) : mixed
Parameters
- $target : string
-
The path name.
- $rmdir : bool = TRUE
- $verbose : bool = TRUE
Tags
cleanFileName()
Remove 32 bit md5 hash prepended to the file suffix.
public
static cleanFileName(mixed $name) : mixed
Note: if the filename was munged with an .unknown
suffix, this removes
the md5 but doesn't undo the munging or remove the .unknown
suffix.
Parameters
- $name : mixed
concat()
Concatenate several files.
public
static concat(array<string|int, mixed> $files[, string $delim = '' ]) : string
Parameters
- $files : array<string|int, mixed>
-
List of file names.
- $delim : string = ''
-
An optional delimiter to put between files.
Return values
stringcopyDir()
public
static copyDir(string $source, string $destination) : mixed
Parameters
- $source : string
- $destination : string
createDir()
Create a directory given a path name, creates parent directories if needed
public
static createDir(string $path[, bool $abort = TRUE ]) : bool|null
Parameters
- $path : string
-
The path name.
- $abort : bool = TRUE
-
Should we abort or just return an invalid code.
Return values
bool|null —NULL: Folder already exists or was not specified. TRUE: Creation succeeded. FALSE: Creation failed.
createFakeFile()
Save a fake file somewhere
public
static createFakeFile(string $dir[, string $contents = 'delete me' ][, string $fileName = NULL ]) : string
Parameters
- $dir : string
-
The directory where the file should be saved.
- $contents : string = 'delete me'
-
Optional: the contents of the file.
- $fileName : string = NULL
Return values
string —The filename saved, or FALSE on failure.
duplicate()
Copies a file
public
static duplicate(mixed $filePath) : mixed
Parameters
- $filePath : mixed
findFiles()
Search directory tree for files which match a glob pattern.
public
static findFiles(string $dir, string $pattern[, bool $relative = FALSE ][, int|null $maxDepth = NULL ]) : mixed
Note: Dot-directories (like "..", ".git", or ".svn") will be ignored.
Parameters
- $dir : string
-
base dir.
- $pattern : string
-
glob pattern, eg "*.txt".
- $relative : bool = FALSE
-
TRUE if paths should be made relative to $dir
- $maxDepth : int|null = NULL
-
Maximum depth of subdirs to check. For no limit, use NULL.
Tags
formatFile()
Format file.
public
static formatFile(array<string|int, mixed> &$param, string $fileName[, array<string|int, mixed> $extraParams = [] ]) : mixed
Parameters
- $param : array<string|int, mixed>
- $fileName : string
- $extraParams : array<string|int, mixed> = []
getAcceptableExtensionsForMimeType()
Get the extensions that this MimeTpe is for
public
static getAcceptableExtensionsForMimeType([string $mimeType = [] ]) : array<string|int, mixed>
Parameters
- $mimeType : string = []
-
the mime-type we want extensions for
Return values
array<string|int, mixed>getExtensionFromPath()
Get the extension of a file based on its path
public
static getExtensionFromPath(string $path) : string
Parameters
- $path : string
-
path of the file to query
Return values
stringgetFilesByExtension()
Get files for the extension.
public
static getFilesByExtension(string $path, string $ext) : array<string|int, mixed>
Parameters
- $path : string
- $ext : string
Return values
array<string|int, mixed>getFileURL()
Return formatted file URL, like for image file return image url with image icon
public
static getFileURL(string $path, string $fileType[, string $url = NULL ]) : string
Parameters
- $path : string
-
Absoulte file path
- $fileType : string
- $url : string = NULL
-
File preview link e.g. https://example.com/civicrm/file?reset=1&filename=image.png&mime-type=image/png
Return values
string —$url
getIconFromMimeType()
Get file icon class for specific MIME Type
public
static getIconFromMimeType(string $mimeType) : string
Parameters
- $mimeType : string
Return values
stringgetImageURL()
Return formatted image icon
public
static getImageURL(string $imageURL) : string
Parameters
- $imageURL : string
-
Contact's image url
Return values
string —$url
getMaxFileSize()
Get the maximum file size permitted for upload.
public
static getMaxFileSize() : int
This function contains logic to check the server setting if none is configured. It is unclear if this is still relevant but perhaps it is no harm-no-foul.
Return values
int —Size in mega-bytes.
isAbsolute()
Determine if a path is absolute.
public
static isAbsolute(string $path) : bool
Parameters
- $path : string
Return values
bool —TRUE if absolute. FALSE if relative.
isAscii()
Given a file name, determine if the file contents make it an ascii file
public
static isAscii(string $name) : bool
Parameters
- $name : string
-
Name of file.
Return values
bool —true if file is ascii
isChildPath()
Determine if $child is a sub-directory of $parent
public
static isChildPath(string $parent, string $child[, bool $checkRealPath = TRUE ]) : bool
Parameters
- $parent : string
- $child : string
- $checkRealPath : bool = TRUE
Return values
boolisDir()
Wrapper for is_dir() to avoid flooding logs when open_basedir is used.
public
static isDir(string|null $dir) : bool|null
Don't use this function as a swap-in replacement for is_dir() for all situations as this might silence errors that you want to know about and would help troubleshoot problems. It should only be used when doing something like iterating over a set of folders where you know some of them might not legitimately exist or might be outside open_basedir because you're trying to find the right one. If you expect the path you're checking to be inside open_basedir, then you should use the regular is_dir(). (e.g. it might not exist but might be something like a cache folder in templates_c, which can't be outside open_basedir, so there you would use regular is_dir).
**** Security alert **** If you change this function so that it would be possible to return TRUE without checking the real value of is_dir() then it opens up a possible security issue. It should either return FALSE, or the value returned from is_dir().
Parameters
- $dir : string|null
Return values
bool|null —In php8 the return value from is_dir() is always bool but in php7 it can be null.
isExtensionSafe()
public
static isExtensionSafe(string $ext) : bool
Parameters
- $ext : string
Return values
boolisIncludable()
Determine whether a given file is listed in the PHP include path.
public
static isIncludable(string $name) : bool
Parameters
- $name : string
-
Name of file.
Return values
bool —whether the file can be include()d or require()d
isValidFileName()
Is the filename a safe and valid filename passed in from URL
public
static isValidFileName([string $fileName = NULL ]) : bool
Parameters
- $fileName : string = NULL
Return values
boolmakeFileName()
Make a valid file name.
public
static makeFileName(string $name[, bool $unicode = FALSE ]) : string
Parameters
- $name : string
- $unicode : bool = FALSE
Return values
stringmakeFilenameWithUnicode()
CRM_Utils_String::munge() doesn't handle unicode and needs to be able to generate valid database tablenames so will sometimes generate a random string. Here what we want is a human-sensible filename that might contain unicode.
public
static makeFilenameWithUnicode(string $input[, string $replacementString = '_' ][, int $cutoffLength = 63 ]) : string
Note that this does filter out emojis and such, but keeps characters that are considered alphanumeric in non-english languages.
Parameters
- $input : string
- $replacementString : string = '_'
-
Character or string to replace invalid characters with. Can be the empty string.
- $cutoffLength : int = 63
-
Length to truncate the result after replacements.
Return values
stringrelativize()
Make a file path relative to some base dir.
public
static relativize(mixed $directory, mixed $basePath) : string
Parameters
- $directory : mixed
- $basePath : mixed
Return values
stringreplaceDir()
Move $fromDir to $toDir, replacing/deleting any pre-existing content.
public
static replaceDir(string $fromDir, string $toDir[, bool $verbose = FALSE ]) : bool
Parameters
- $fromDir : string
-
The directory which should be moved.
- $toDir : string
-
The new location of the directory.
- $verbose : bool = FALSE
Return values
bool —TRUE on success
resizeImage()
Resize an image.
public
static resizeImage(string $sourceFile, int $targetWidth, int $targetHeight[, string $suffix = "" ][, bool $preserveAspect = TRUE ]) : string
Parameters
- $sourceFile : string
-
Filesystem path to existing image on server
- $targetWidth : int
-
New width desired, in pixels
- $targetHeight : int
-
New height desired, in pixels
- $suffix : string = ""
-
= "" If supplied, the image will be renamed to include this suffix. For example if the original file name is "foo.png" and $suffix = "_bar", then the final file name will be "foo_bar.png".
- $preserveAspect : bool = TRUE
-
= TRUE When TRUE $width and $height will be used as a bounding box, outside of which the resized image will not extend. When FALSE, the image will be resized exactly to $width and $height, even if it means stretching it.
Tags
Return values
string —Path to image
restrictAccess()
Restrict access to a given directory (by planting there a restrictive .htaccess file)
public
static restrictAccess(string $dir[, bool $overwrite = FALSE ]) : mixed
Parameters
- $dir : string
-
The directory to be secured.
- $overwrite : bool = FALSE
restrictBrowsing()
Restrict remote users from browsing the given directory.
public
static restrictBrowsing(mixed $publicDir) : mixed
Parameters
- $publicDir : mixed
runSqlQuery()
Runs an SQL query.
public
static runSqlQuery(string|null $dsn, string $queryString[, string $prefix = NULL ][, bool $dieOnErrors = TRUE ]) : mixed
Parameters
- $dsn : string|null
- $queryString : string
- $prefix : string = NULL
- $dieOnErrors : bool = TRUE
Tags
sourceSQLFile()
public
static sourceSQLFile(string|null $dsn, string $fileName[, string $prefix = NULL ][, bool $dieOnErrors = TRUE ]) : mixed
Parameters
- $dsn : string|null
-
Use NULL to load the default/active connection from CRM_Core_DAO. Otherwise, give a full DSN string.
- $fileName : string
- $prefix : string = NULL
- $dieOnErrors : bool = TRUE
stripComments()
Strips comment from a possibly multiline SQL string
public
static stripComments(string $string) : string
Parameters
- $string : string
Return values
string —stripped string
tempdir()
Create a path to a temporary directory which can endure for multiple requests.
public
static tempdir([string $prefix = 'tmp-' ]) : mixed
Parameters
- $prefix : string = 'tmp-'
Tags
tempnam()
Create a path to a temporary file which can endure for multiple requests.
public
static tempnam([string $prefix = 'tmp-' ]) : mixed
Parameters
- $prefix : string = 'tmp-'
Tags
toUtf8()
Given a file name, recode it (in place!) to UTF-8
public
static toUtf8(string $name) : bool
Parameters
- $name : string
-
Name of file.
Return values
bool —whether the file was recoded properly
findPathDepth()
Determine the absolute depth of a path expression.
private
static findPathDepth(string $path) : int
Parameters
- $path : string
-
Ex: '/var/www/foo'
Return values
int —Ex: 3
try_unlink()
Helper function to avoid repetition in cleanDir: execute unlink and produce a warning on failure.
private
static try_unlink(mixed $object, mixed $description) : mixed
Parameters
- $object : mixed
- $description : mixed