Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
9.42% covered (danger)
9.42%
18 / 191
9.09% covered (danger)
9.09%
2 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Page_Cache_Setup
9.42% covered (danger)
9.42%
18 / 191
9.09% covered (danger)
9.09%
2 / 22
3606.83
0.00% covered (danger)
0.00%
0 / 1
 run_setup
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
56
 enable
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_notices
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_notice
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 run_step
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 enable_caching
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 verify_wp_content_writable
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 verify_permalink_setting
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 create_settings_file
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_advanced_cache_path
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 create_advanced_cache
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
72
 add_wp_cache_define
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
42
 can_run_cache
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 deactivate
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 uninstall
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 delete_advanced_cache
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 delete_wp_cache_constant
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 cleanup_wp_cache_constant
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 find_wp_config
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 clear_opcache
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 write_to_file_direct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_wp_filesystem
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache;
4
5use Automattic\Jetpack_Boost\Lib\Analytics;
6use Automattic\Jetpack_Boost\Lib\Super_Cache_Config_Compatibility;
7use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Error;
8use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings;
9use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Filesystem_Utils;
10use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Logger;
11
12class Page_Cache_Setup {
13
14    private static $notices = array();
15
16    /**
17     * Runs setup steps and returns whether setup was successful or not.
18     *
19     * @return bool|\WP_Error
20     */
21    public static function run_setup() {
22        // Steps that are only for cache system verification. They don't change anything.
23        $verification_steps = array(
24            'verify_wp_content_writable',
25            'verify_permalink_setting',
26        );
27
28        foreach ( $verification_steps as $step ) {
29            $result = self::run_step( $step );
30
31            if ( is_wp_error( $result ) ) {
32                return $result;
33            }
34        }
35
36        /*
37         * Steps that may change something to setup the cache system.
38         * Each of them should return the result in following format:
39         * - true if the step was successful and changes were made
40         * - false if the step was successful but no changes were made
41         * - WP_Error if the step failed
42         */
43        $setup_steps = array(
44            'create_settings_file',
45            'create_advanced_cache',
46            'add_wp_cache_define',
47            'enable_caching',
48        );
49
50        $changes_made = false;
51        foreach ( $setup_steps as $step ) {
52            $result = self::run_step( $step );
53
54            if ( is_wp_error( $result ) ) {
55                return $result;
56            }
57
58            if ( $result === true ) {
59                $changes_made = true;
60            }
61        }
62
63        if ( $changes_made ) {
64            Analytics::record_user_event( 'page_cache_setup_succeeded' );
65        }
66        return true;
67    }
68
69    /**
70     * Runs setup, then turns caching on and schedules its garbage collection.
71     *
72     * This is what turning Page Cache on means, from the settings screen, the CLI or an ability.
73     *
74     * @return true|\WP_Error
75     */
76    public static function enable() {
77        $setup_result = self::run_setup();
78        if ( is_wp_error( $setup_result ) ) {
79            return $setup_result;
80        }
81
82        Garbage_Collection::activate();
83        Boost_Cache_Settings::get_instance()->set( array( 'enabled' => true ) );
84        return true;
85    }
86
87    public static function get_notices() {
88        return self::$notices;
89    }
90
91    private static function add_notice( $title, $message ) {
92        self::$notices[] = array(
93            'title'   => $title,
94            'message' => $message,
95        );
96    }
97
98    private static function run_step( $step ) {
99        $result = self::$step();
100
101        if ( $result instanceof Boost_Cache_Error ) {
102            Analytics::record_user_event( 'page_cache_setup_failed', array( 'error_code' => $result->get_error_code() ) );
103            return $result->to_wp_error();
104        }
105
106        if ( is_wp_error( $result ) ) {
107            Analytics::record_user_event( 'page_cache_setup_failed', array( 'error_code' => $result->get_error_code() ) );
108            return $result;
109        }
110    }
111
112    /**
113     * Enable caching step of setup.
114     *
115     * @return Boost_Cache_Error|bool - True on success, false if it was already enabled, error otherwise.
116     */
117    private static function enable_caching() {
118        $settings       = Boost_Cache_Settings::get_instance();
119        $previous_value = $settings->get_enabled();
120
121        if ( $previous_value === true ) {
122            return false;
123        }
124
125        $enabled_result = $settings->set( array( 'enabled' => true ) );
126
127        if ( $enabled_result === true ) {
128            Logger::debug( 'Caching enabled in cache config' );
129        }
130
131        return $enabled_result;
132    }
133
134    /**
135     * Returns true if the wp-content directory is writeable.
136     */
137    private static function verify_wp_content_writable() {
138        $filename = WP_CONTENT_DIR . '/' . uniqid() . '.txt';
139        $result   = @file_put_contents( $filename, 'test' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
140        wp_delete_file( $filename );
141
142        if ( $result === false ) {
143            return new \WP_Error( 'wp-content-not-writable' );
144        }
145
146        return true;
147    }
148
149    /**
150     * Returns true if WordPress is using a proper permalink setup. WP_Error if not.
151     */
152    private static function verify_permalink_setting() {
153        global $wp_rewrite;
154
155        if ( ! $wp_rewrite || ! $wp_rewrite->using_permalinks() ) {
156            return new \WP_Error( 'not-using-permalinks' );
157        }
158    }
159
160    /**
161     * Create a settings file, if one does not already exist.
162     *
163     * @return bool|\WP_Error - True if the file was created, WP_Error if there was a problem, or false if the file already exists.
164     */
165    private static function create_settings_file() {
166        $result = Boost_Cache_Settings::get_instance()->create_settings_file();
167        return $result;
168    }
169
170    /**
171     * Get the path to the advanced-cache.php file.
172     *
173     * @return string The full path to the advanced-cache.php file.
174     */
175    public static function get_advanced_cache_path() {
176        return WP_CONTENT_DIR . '/advanced-cache.php';
177    }
178
179    /**
180     * Creates the advanced-cache.php file.
181     *
182     * Returns true if the files were setup correctly, or WP_Error if there was a problem.
183     *
184     * @return bool|\WP_Error
185     */
186    private static function create_advanced_cache() {
187        $advanced_cache_filename = self::get_advanced_cache_path();
188
189        if ( file_exists( $advanced_cache_filename ) ) {
190            $content = file_get_contents( $advanced_cache_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
191
192            if ( strpos( $content, 'WP SUPER CACHE' ) !== false ) {
193                // advanced-cache.php is already in use by WP Super Cache.
194
195                if ( Super_Cache_Config_Compatibility::is_compatible() ) {
196                    $deactivation = new Data_Sync_Actions\Deactivate_WPSC();
197                    $deactivation->handle();
198                    self::add_notice(
199                        __( 'WP Super Cache Has Been Deactivated', 'jetpack-boost' ),
200                        __( 'To ensure optimal performance, WP Super Cache has been automatically deactivated because Jetpack Boost\'s Cache is now active. Only one caching system can be used at a time.', 'jetpack-boost' )
201                    );
202
203                    Analytics::record_user_event(
204                        'switch_to_boost_cache',
205                        array(
206                            'type'   => 'silent',
207                            'reason' => 'super_cache_compatible',
208                        )
209                    );
210                } else {
211                    return new \WP_Error( 'advanced-cache-for-super-cache' );
212                }
213            } elseif ( strpos( $content, Page_Cache::ADVANCED_CACHE_SIGNATURE ) === false ) {
214                // advanced-cache.php is in use by another plugin.
215                return new \WP_Error( 'advanced-cache-incompatible' );
216            }
217
218            if ( strpos( $content, Page_Cache::ADVANCED_CACHE_VERSION ) !== false ) {
219                // The advanced-cache.php file belongs to current version of Boost Cache.
220                return false;
221            }
222        }
223
224        $plugin_dir_name      = untrailingslashit( str_replace( JETPACK_BOOST_PLUGIN_FILENAME, '', JETPACK_BOOST_PLUGIN_BASE ) );
225        $boost_cache_filename = WP_CONTENT_DIR . '/plugins/' . $plugin_dir_name . '/app/modules/optimizations/page-cache/pre-wordpress/class-boost-cache.php';
226        if ( ! file_exists( $boost_cache_filename ) ) {
227            return new \WP_Error( 'boost-cache-file-not-found' );
228        }
229        $contents = '<?php
230// ' . Page_Cache::ADVANCED_CACHE_SIGNATURE . ' - ' . Page_Cache::ADVANCED_CACHE_VERSION . '
231if ( ! file_exists( \'' . $boost_cache_filename . '\' ) ) {
232return;
233}
234require_once( \'' . $boost_cache_filename . '\');
235$boost_cache = new Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache();
236$boost_cache->init_actions();
237$boost_cache->serve();
238';
239
240        $write_advanced_cache = Filesystem_Utils::write_to_file( $advanced_cache_filename, $contents );
241        if ( $write_advanced_cache instanceof Boost_Cache_Error ) {
242            return new \WP_Error( 'unable-to-write-to-advanced-cache', $write_advanced_cache->get_error_code() );
243        }
244        self::clear_opcache( $advanced_cache_filename );
245
246        Logger::debug( 'Advanced cache file created' );
247
248        return true;
249    }
250
251    /**
252     * Adds the WP_CACHE define to wp-config.php
253     */
254    private static function add_wp_cache_define() {
255        $config_file = self::find_wp_config();
256        if ( $config_file === false ) {
257            return new \WP_Error( 'wp-config-not-found' );
258        }
259
260        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
261        $content = file_get_contents( $config_file );
262        if ( preg_match( '#^\s*(define\s*\(\s*[\'"]WP_CACHE[\'"]|const\s+WP_CACHE\s*=)#m', $content ) === 1 ) {
263            /*
264             * wp-settings.php checks "if ( WP_CACHE )" so it may be truthy and
265             * not === true to pass that check.
266             * Later, it is defined as false in default-constants.php, but
267             * it may have been defined manually as true using "true", 1, or "1"
268             * in wp-config.php.
269             */
270            if ( defined( 'WP_CACHE' ) && ! WP_CACHE ) {
271                return new \WP_Error( 'wp-cache-defined-not-true' );
272            }
273
274            return false; // WP_CACHE already added.
275        }
276        $content = preg_replace(
277            '#^<\?php#',
278            '<?php
279define( \'WP_CACHE\', true ); // ' . Page_Cache::ADVANCED_CACHE_SIGNATURE,
280            $content
281        );
282
283        $result = self::write_to_file_direct( $config_file, $content );
284        if ( $result === false ) {
285            return new \WP_Error( 'wp-config-not-writable' );
286        }
287        self::clear_opcache( $config_file );
288
289        Logger::debug( 'WP_CACHE constant added to wp-config.php' );
290
291        return true;
292    }
293
294    /**
295     * Checks if page cache can be run or not.
296     *
297     * @return bool True if the advanced-cache.php file doesn't exist or belongs to Boost, false otherwise.
298     */
299    public static function can_run_cache() {
300        $advanced_cache_path = self::get_advanced_cache_path();
301        if ( ! file_exists( $advanced_cache_path ) ) {
302            return true;
303        }
304
305        $content = file_get_contents( $advanced_cache_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
306        return strpos( $content, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false;
307    }
308
309    /**
310     * Removes the advanced-cache.php file and the WP_CACHE define from wp-config.php
311     * Fired when the plugin is deactivated.
312     */
313    public static function deactivate() {
314        $advanced_cache_deleted = self::delete_advanced_cache();
315        // Only remove constant if Boost was the last to run caching.
316        // This is to avoid breaking caching for other plugins.
317        if ( $advanced_cache_deleted ) {
318            self::delete_wp_cache_constant();
319        } else {
320            self::cleanup_wp_cache_constant();
321        }
322
323        return true;
324    }
325
326    /**
327     * Removes the boost-cache directory, removing all cached files and the config file.
328     * Fired when the plugin is uninstalled.
329     */
330    public static function uninstall() {
331        self::deactivate();
332        // Call the Cache Preload module deactivation here to ensure it's cleaned up properly.
333        Cache_Preload::deactivate();
334        $result = Filesystem_Utils::delete_directory( WP_CONTENT_DIR . '/boost-cache' );
335        if ( $result instanceof Boost_Cache_Error ) {
336            return $result->to_wp_error();
337        }
338
339        return true;
340    }
341
342    /**
343     * Deletes the file advanced-cache.php if it exists.
344     */
345    public static function delete_advanced_cache() {
346        $advanced_cache_filename = self::get_advanced_cache_path();
347
348        if ( ! file_exists( $advanced_cache_filename ) ) {
349            return false;
350        }
351
352        $deleted_file = false;
353        $content      = file_get_contents( $advanced_cache_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
354        if ( strpos( $content, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false ) {
355            wp_delete_file( $advanced_cache_filename );
356
357            // wp_delete_file doesn't return anything
358            // so we manually check if the file was deleted.
359            $deleted_file = ! file_exists( $advanced_cache_filename );
360        }
361
362        self::clear_opcache( $advanced_cache_filename );
363
364        return $deleted_file;
365    }
366
367    /**
368     * Deletes the WP_CACHE define from wp-config.php
369     *
370     * @return \WP_Error if an error occurred.
371     */
372    public static function delete_wp_cache_constant() {
373        $config_file = self::find_wp_config();
374        if ( $config_file === false ) {
375            return;
376        }
377
378        $lines = file( $config_file );
379        $found = false;
380        foreach ( $lines as $key => $line ) {
381            if ( preg_match( '#define\s*\(\s*[\'"]WP_CACHE[\'"]#', $line ) === 1 && strpos( $line, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false ) {
382                unset( $lines[ $key ] );
383                $found = true;
384            }
385        }
386        if ( ! $found ) {
387            return;
388        }
389        $content = implode( '', $lines );
390        Filesystem_Utils::write_to_file( $config_file, $content );
391        self::clear_opcache( $config_file );
392    }
393
394    /**
395     * Removes the comment after WP_CACHE defined in wp-config.php (if any).
396     *
397     * @return void
398     */
399    public static function cleanup_wp_cache_constant() {
400        $config_file = self::find_wp_config();
401        if ( $config_file === false ) {
402            return;
403        }
404
405        $lines = file( $config_file );
406        $found = false;
407        foreach ( $lines as $key => $line ) {
408            if ( preg_match( '#define\s*\(\s*[\'"]WP_CACHE[\'"]#', $line ) === 1 && strpos( $line, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false ) {
409                $lines[ $key ] = preg_replace( '#\s*?\/\/.*$#', '', $line );
410                $found         = true;
411            }
412        }
413        if ( ! $found ) {
414            return;
415        }
416        $content = implode( '', $lines );
417        Filesystem_Utils::write_to_file( $config_file, $content );
418        self::clear_opcache( $config_file );
419    }
420
421    /**
422     * Find location of wp-config.php file.
423     *
424     * @return string|false - The path to the wp-config.php file, or false if it was not found.
425     */
426    private static function find_wp_config() {
427        if ( file_exists( ABSPATH . 'wp-config.php' ) ) {
428            return ABSPATH . 'wp-config.php';
429        } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
430            // While checking one directory up, check for wp-settings.php as well similar to WordPress core, to avoid nested WordPress installations.
431            return dirname( ABSPATH ) . '/wp-config.php';
432        }
433
434        return false;
435    }
436
437    /**
438     * Clear opcache for a file.
439     */
440    private static function clear_opcache( $file ) {
441        // If API functions are restricted, we can't do anything.
442        if ( ini_get( 'opcache.restrict_api' ) ) {
443            return;
444        }
445
446        if ( function_exists( 'opcache_invalidate' ) ) {
447            opcache_invalidate( $file, true );
448        }
449    }
450
451    private static function write_to_file_direct( $file, $content ) {
452        $filesystem = self::get_wp_filesystem();
453        $chmod      = $filesystem->getchmod( $file );
454        if ( $chmod === false ) {
455            $chmod = 0644; // Default to a common permission for files
456        } else {
457            $chmod = intval( '0' . $chmod, 8 ); // Ensure leading zero
458        }
459        return $filesystem->put_contents( $file, $content, $chmod );
460    }
461
462    private static function get_wp_filesystem() {
463        require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
464        require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
465        return new \WP_Filesystem_Direct( null );
466    }
467}