Add Write File Check to detect plugin directory writes #1137
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #665
Implements a new check to detect when plugins save data in the plugin folder.
Plugin folders are deleted when upgraded, so using them to store any data is problematic. This check helps developers identify these issues and directs them to use the uploads directory or database instead.
Changes Made
1. WriteFileSniff (PHPCS Sniff)
Created
phpcs-sniffs/PluginCheck/Sniffs/CodeAnalysis/WriteFileSniff.php:AbstractFunctionParameterSniffto detect file write functionsfwrite,fputs,file_put_contents,touch,copy,rename,copy_dir,move_dir,unzip_fileWP_PLUGIN_DIR,WP_PLUGIN_URL,PLUGINDIR,WPINC,WP_CONTENT_DIR,WP_CONTENT_URLplugins_url(),plugin_dir_path(),plugin_dir_url()__FILE__,__DIR__wp_upload_dir(),wp_tempnam(),get_temp_dir()2. Write_File_Check Class
Updated
includes/Checker/Checks/Plugin_Repo/Write_File_Check.php:3. Test Coverage
Test Plugins:
test-plugin-write-file-with-errors/: Contains 7 examples of incorrect usagetest-plugin-write-file-without-errors/: Contains examples of correct usagePHPUnit Tests:
Write_File_Check_Tests.php: Tests the check classWriteFileUnitTest.phpandWriteFileUnitTest.inc: Tests the sniff directly4. Configuration
PluginCheck.CodeAnalysis.WriteFilerule tophpcs-sniffs/PluginCheck/ruleset.xmlLimitations
The sniff uses static analysis and can only detect file write operations where the path is directly specified in the function call. It cannot detect:
This limitation is acceptable as it catches the most common cases.
Related Resources
Acknowledgments
This check is based on the
calls_write_file_warningdetection logic from the internal plugin review scanner developed by @frantorres, which has been successfully identifying these issues during manual reviews. This implementation makes that same detection available to plugin developers as an automated check.