Automattic\WooCommerce\Internal\Utilities

FilesystemUtil::get_wp_filesystem_directpublic staticWC 11.0.0

Get a direct filesystem instance, bypassing the configured FS_METHOD.

This is appropriate for paths that are guaranteed to be writable by the web server process (such as anything inside the uploads directory). Using the configured FS_METHOD for those paths is unnecessary and breaks on sites where FS_METHOD is set to an FTP-based method without complete credentials, even though the target paths are directly writable.

Defensive fallback: if WP_Filesystem_Direct cannot be loaded or instantiated, fall back to {@see self::get_wp_filesystem()} with a _doing_it_wrong notice.

Method of the class: FilesystemUtil{}

No Hooks.

Returns

WP_Filesystem_Base. Normally a WP_Filesystem_Direct instance.

Usage

$result = FilesystemUtil::get_wp_filesystem_direct(): WP_Filesystem_Base;

Changelog

Since 11.0.0 Introduced.

FilesystemUtil::get_wp_filesystem_direct() code WC 11.0.1

public static function get_wp_filesystem_direct(): WP_Filesystem_Base {
	if ( null !== self::$cached_direct_filesystem ) {
		return self::$cached_direct_filesystem;
	}

	// require_once is a no-op if the class is already loaded, so no class_exists guard is needed.
	require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
	require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

	if ( class_exists( WP_Filesystem_Direct::class ) ) {
		try {
			// WP_Filesystem_Direct::chmod()/put_contents() use the FS_CHMOD_* constants when no mode is
			// passed; core only defines them in WP_Filesystem(), which we skip, so mirror them here.
			if ( ! defined( 'FS_CHMOD_DIR' ) ) {
				define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
			}
			if ( ! defined( 'FS_CHMOD_FILE' ) ) {
				define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
			}

			self::$cached_direct_filesystem = new WP_Filesystem_Direct( null );
			return self::$cached_direct_filesystem;
		} catch ( \Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Fall through to the fallback below.
		}
	}

	_doing_it_wrong(
		__METHOD__,
		esc_html__( 'WP_Filesystem_Direct could not be loaded. Falling back to the configured FS_METHOD; operations on the uploads directory may fail if FS_METHOD is misconfigured.', 'woocommerce' ),
		'11.0.0'
	);

	// Deliberately uncached: the fallback may be a non-direct (FTP) instance, and caching it would pin
	// every later "direct" caller to FS_METHOD; leaving it uncached lets a later call retry direct.
	return self::get_wp_filesystem();
}