rmdir( $dir );
}
/**
* Deletes work folders left behind by crashed workers.
*
* @param int $older_than_seconds Minimum age of a folder to remove.
* @return int Number of folders removed.
*/
public static function clean_temp( int $older_than_seconds = DAY_IN_SECONDS ): int {
$base = self::uploads_base() . '/' . self::TEMP_DIR;
$removed = 0;
$entries = is_dir( $base ) ? scandir( $base ) : false;
foreach ( false === $entries ? array() : $entries as $entry ) {
$child = $base . '/' . $entry;
if ( '.' === $entry || '..' === $entry || ! is_dir( $child ) ) {
continue;
}
if ( time() - (int) filemtime( $child ) >= $older_than_seconds ) {
self::remove_work_dir( $child );
++$removed;
}
}
return $removed;
}
/**
* Adds deny rules for Apache/LiteSpeed and a blank index to a directory.
*
* @param string $dir Directory to protect.
* @return void
*/
public static function protect_dir( string $dir ): void {
$htaccess = $dir . '/.htaccess';
if ( ! file_exists( $htaccess ) ) {
file_put_contents( $htaccess, "\n\tRequire all denied\n\n\n\tOrder allow,deny\n\tDeny from all\n\n" );
}
$index = $dir . '/index.php';
if ( ! file_exists( $index ) ) {
file_put_contents( $index, "chmod( $target, $perms & 0777 );
}
clearstatcache( true, $target );
return true;
}
/**
* Returns direct filesystem access.
*
* Image files are local and PHP must write them itself, so this never uses an FTP-backed WP_Filesystem.
*
* @return \WP_Filesystem_Direct
*/
public static function filesystem(): \WP_Filesystem_Direct {
static $filesystem = null;
if ( null === $filesystem ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
$filesystem = new \WP_Filesystem_Direct( null );
}
return $filesystem;
}
/**
* Resolves a possibly non-existent path through its deepest existing ancestor.
*
* @param string $path Path to resolve.
* @return string|null
*/
private static function resolve( string $path ): ?string {
$suffix = array();
$current = $path;
while ( false === realpath( $current ) ) {
$name = basename( $current );
if ( '..' === $name ) {
return null;
}
array_unshift( $suffix, $name );
$parent = dirname( $current );
if ( $parent === $current ) {
return null;
}
$current = $parent;
}
$real = (string) realpath( $current );
return array() === $suffix ? $real : untrailingslashit( $real ) . '/' . implode( '/', $suffix );
}
}