Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.09% covered (warning)
84.09%
74 / 88
50.00% covered (danger)
50.00%
4 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
File_Storage
84.09% covered (warning)
84.09%
74 / 88
50.00% covered (danger)
50.00%
4 / 8
37.38
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 write
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 reset_rebuild_file
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
8.12
 read
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
5.25
 garbage_collect
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_uri_directory
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_path
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 clear
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
12
1<?php
2/*
3 * This file may be called before WordPress is fully initialized. See the README file for info.
4 */
5
6namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Storage;
7
8use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Error;
9use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Utils;
10use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Filesystem_Utils;
11use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Logger;
12use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Path_Actions\Filter_Older;
13use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Path_Actions\Rebuild_File;
14use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Path_Actions\Simple_Delete;
15use SplFileInfo;
16
17/**
18 * File Storage - handles writing to disk, reading from disk, purging and pruning old content.
19 */
20class File_Storage implements Storage {
21
22    /**
23     * @var string - The root path where all cached files go.
24     */
25    private $root_path;
26
27    public function __construct( $root_path ) {
28        $this->root_path = WP_CONTENT_DIR . '/boost-cache/cache/' . Boost_Cache_Utils::sanitize_file_path( Boost_Cache_Utils::trailingslashit( $root_path ) );
29    }
30
31    /**
32     * Given a request_uri and its parameters, store the given data in the cache.
33     *
34     * @param string $request_uri - The URI of this request (excluding GET parameters)
35     * @param array  $parameters  - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally.
36     * @param string $data        - The data to write to disk.
37     */
38    public function write( $request_uri, $parameters, $data ) {
39        $directory = self::get_uri_directory( $request_uri );
40        $filename  = Filesystem_Utils::get_request_filename( $request_uri, $parameters );
41        if ( false === $filename ) {
42            return new Boost_Cache_Error( 'cannot-build-cache-key', 'Could not build cache key' );
43        }
44
45        if ( ! Filesystem_Utils::create_directory( $directory ) ) {
46            return new Boost_Cache_Error( 'cannot-create-cache-dir', 'Could not create cache directory' );
47        }
48
49        return Filesystem_Utils::write_to_file( $directory . $filename, $data );
50    }
51
52    /**
53     * Given a request_uri and its parameters, reset the filename of a rebuild
54     * cache file and return true, or false otherwise.
55     * If a rebuild file is too old, it will be deleted and false will be returned.
56     *
57     * @param string $request_uri - The URI of this request (excluding GET parameters)
58     * @param array  $parameters  - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally.
59     */
60    public function reset_rebuild_file( $request_uri, $parameters ) {
61        $directory = self::get_uri_directory( $request_uri );
62        $filename  = Filesystem_Utils::get_request_filename( $request_uri, $parameters );
63        if ( false === $filename ) {
64            return false;
65        }
66        $hash_path = $directory . $filename . Filesystem_Utils::REBUILD_FILE_EXTENSION;
67
68        if ( file_exists( $hash_path ) ) {
69            $expired = ( @filemtime( $hash_path ) + JETPACK_BOOST_CACHE_REBUILD_DURATION ) <= time(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
70
71            if ( $expired ) {
72                if ( Filesystem_Utils::delete_file( $hash_path ) ) {
73                    Logger::debug( "Deleted expired rebuilt file: $hash_path" );
74                } else {
75                    Logger::debug( "Could not delete expired rebuilt file: $hash_path" );
76                }
77                return false;
78            }
79
80            if ( Filesystem_Utils::restore_file( $hash_path ) ) {
81                Logger::debug( "Restored rebuilt file: $hash_path" );
82                return true;
83            } else {
84                Logger::debug( "Could not restore rebuilt file: $hash_path" );
85                return false;
86            }
87        }
88        return false;
89    }
90
91    /**
92     * Given a request_uri and its parameters, return any stored data from the cache, or false otherwise.
93     *
94     * @param string $request_uri - The URI of this request (excluding GET parameters)
95     * @param array  $parameters  - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally.
96     */
97    public function read( $request_uri, $parameters ) {
98        $directory = self::get_uri_directory( $request_uri );
99        $filename  = Filesystem_Utils::get_request_filename( $request_uri, $parameters );
100        if ( false === $filename ) {
101            return false;
102        }
103        $hash_path = $directory . $filename;
104
105        if ( file_exists( $hash_path ) ) {
106            $filemtime = @filemtime( $hash_path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
107            $expired   = ( $filemtime + JETPACK_BOOST_CACHE_DURATION ) <= time();
108
109            // If file exists and is not expired, return the file contents.
110            if ( ! $expired ) {
111                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, WordPress.Security.EscapeOutput.OutputNotEscaped
112                return file_get_contents( $hash_path );
113            }
114
115            // If file exists but is expired, delete it.
116            if ( Filesystem_Utils::delete_file( $hash_path ) ) {
117                Logger::debug( "Deleted expired file: $hash_path" );
118            } else {
119                Logger::debug( "Could not delete expired file: $hash_path" );
120            }
121        }
122
123        return false;
124    }
125
126    /**
127     * Garbage collect expired files.
128     *
129     * @param int $cache_ttl If file is is created before this specified number of seconds, it will be deleted.
130     */
131    public function garbage_collect( $cache_ttl = JETPACK_BOOST_CACHE_DURATION ) {
132        if ( $cache_ttl === -1 ) {
133            // Garbage collection is disabled.
134            return false;
135        }
136
137        $created_before = time() - $cache_ttl;
138
139        $count = Filesystem_Utils::iterate_directory( $this->root_path, new Filter_Older( $created_before, new Rebuild_File() ) );
140        if ( $count instanceof Boost_Cache_Error ) {
141            Logger::debug( 'Garbage collection failed: ' . $count->get_error_message() );
142            return false;
143        }
144
145        Logger::debug( "Garbage collected $count files" );
146        return $count;
147    }
148
149    /**
150     * Given a request_uri, return the filesystem path where it should get stored. Handles sanitization.
151     * Note that the directory path does not take things like GET parameters or cookies into account, for easy cache purging.
152     *
153     * @param string $request_uri - The URI of this request (excluding GET parameters)
154     */
155    private function get_uri_directory( $request_uri ) {
156        return Boost_Cache_Utils::trailingslashit( $this->root_path . self::sanitize_path( $request_uri ) );
157    }
158
159    /**
160     * Sanitize a path for safe usage on the local filesystem.
161     *
162     * @param string $path - The path to sanitize.
163     */
164    private function sanitize_path( $path ) {
165        static $_cache = array();
166        if ( isset( $_cache[ $path ] ) ) {
167            return $_cache[ $path ];
168        }
169
170        $path = Boost_Cache_Utils::sanitize_file_path( $path );
171
172        $_cache[ $path ] = $path;
173        return $path;
174    }
175
176    /**
177     * Delete cache based on given parameters.
178     *
179     * @param string $path - The URL or path to delete the cache for.
180     * @param array  $args - The parameters defining the cache filename.
181     * Example:
182     * array(
183     *  'rebuild' => (boolean) default true - If true, cache files will be rebuilt instead of being deleted.
184     *  'parameters' => false | array, default false - If array is provided, the files created for that specific request matching the parameter will be effected. If parameter is provided, recursive is ignored and considered as false.
185     *  'recursive' => (boolean) default false - If true, the cache will be deleted recursively in subdirectories.
186     * )
187     */
188    public function clear( $path, $args = array() ) {
189        if ( ! is_string( $path ) ) {
190            return;
191        }
192        $path = trim( $path );
193        if ( '' === $path || 0 !== preg_match( '/[[:cntrl:]]/', $path ) ) {
194            return;
195        }
196        // Two leading slashes can introduce a URL host; three or more denote a request path.
197        if ( 0 === strpos( $path, '///' ) ) {
198            $path = '/' . ltrim( $path, '/' );
199        }
200        $request_uri = parse_url( $path, PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url
201        if ( false === $request_uri ) {
202            return;
203        }
204        $request_uri = Boost_Cache_Utils::normalize_request_uri( $request_uri ?? '/' );
205        if ( false === $request_uri ) {
206            return;
207        }
208        $normalized_path = self::get_uri_directory( $request_uri );
209
210        // Ensure the path is within the cache directory
211        if ( strpos( $normalized_path, $this->root_path ) !== 0 ) {
212            Logger::debug( 'Attempted to delete cache for path outside of cache directory: ' . $path );
213            return;
214        }
215
216        $recursive  = $args['recursive'] ?? false;
217        $rebuild    = $args['rebuild'] ?? true;
218        $parameters = $args['parameters'] ?? false;
219
220        if ( $rebuild ) {
221            $action = new Rebuild_File();
222        } else {
223            $action = new Simple_Delete();
224        }
225
226        // If parameters are provided, delete the specific file and skip any iteration.
227        if ( $parameters ) {
228            $filename = Filesystem_Utils::get_request_filename( $request_uri, $parameters );
229            if ( false === $filename ) {
230                return;
231            }
232            $action->apply_to_path( new SplFileInfo( $normalized_path . $filename ) );
233            return;
234        }
235
236        if ( $recursive ) {
237            Filesystem_Utils::iterate_directory( $normalized_path, $action );
238        } else {
239            Filesystem_Utils::iterate_files( $normalized_path, $action );
240        }
241    }
242}