Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
57.92% covered (warning)
57.92%
106 / 183
11.11% covered (danger)
11.11%
1 / 9
CRAP
n/a
0 / 0
jetpack_boost_handle_minify_request
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
9
jetpack_boost_check_404_handler
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
jetpack_boost_404_tester_cron
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
jetpack_boost_404_tester
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
jetpack_boost_404_setup
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
jetpack_boost_page_optimize_cleanup_cache
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
jetpack_boost_minify_remove_stale_static_files
42.11% covered (danger)
42.11%
8 / 19
0.00% covered (danger)
0.00%
0 / 1
24.72
jetpack_boost_build_minify_output
63.33% covered (warning)
63.33%
57 / 90
0.00% covered (danger)
0.00%
0 / 1
55.81
jetpack_boost_minify_get_file_parts
40.00% covered (danger)
40.00%
8 / 20
0.00% covered (danger)
0.00%
0 / 1
13.78
1<?php
2
3use Automattic\Jetpack_Boost\Admin\Config as Boost_Admin_Config;
4use Automattic\Jetpack_Boost\Lib\Minify;
5use Automattic\Jetpack_Boost\Lib\Minify\Config;
6use Automattic\Jetpack_Boost\Lib\Minify\File_Paths;
7use Automattic\Jetpack_Boost\Lib\Minify\Utils;
8
9if ( ! defined( 'JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH' ) ) {
10    define( 'JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH', '/wp-content/boost-cache/static/testing_404.js' );
11}
12
13function jetpack_boost_handle_minify_request( $request_uri ) {
14    // We handle the cache here, tell other caches not to.
15    if ( ! defined( 'DONOTCACHEPAGE' ) ) {
16        define( 'DONOTCACHEPAGE', true );
17    }
18
19    $output  = jetpack_boost_build_minify_output( $request_uri );
20    $content = $output['content'];
21    $headers = $output['headers'];
22
23    foreach ( $headers as $header ) {
24        header( $header );
25    }
26
27    // Check if we're on Atomic and take advantage of the Atomic Edge Cache.
28    if ( defined( 'ATOMIC_CLIENT_ID' ) ) {
29        header( 'A8c-Edge-Cache: cache' );
30    }
31
32    header( 'X-Page-Optimize: uncached' );
33    header( 'Cache-Control: max-age=' . 31536000 );
34    header( 'ETag: "' . md5( $content ) . '"' );
35
36    echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- We need to trust this unfortunately.
37
38    // Cache the generated data, if possible.
39    $use_cache = Config::can_use_static_cache();
40    if ( $use_cache ) {
41        $file_parts = jetpack_boost_minify_get_file_parts( $request_uri );
42        if ( is_array( $file_parts ) && isset( $file_parts['file_name'] ) && isset( $file_parts['file_extension'] ) ) {
43            $cache_dir       = Config::get_static_cache_dir_path();
44            $cache_file_path = $cache_dir . '/' . $file_parts['file_name'] . '.min.' . $file_parts['file_extension'];
45
46            if ( jetpack_boost_page_optimize_cache_has_room( $cache_dir . '/*.min.*', strlen( $content ) ) ) {
47                jetpack_boost_page_optimize_write_cache_file( $cache_file_path, $content );
48            }
49        }
50    }
51}
52
53/**
54 * Using a crafted request, we can check if is_404() is working in wp-content/
55 * The constant JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH is the path to the file that will be requested.
56 */
57function jetpack_boost_check_404_handler( $request_uri ) {
58    if ( ! str_contains( strtolower( $request_uri ), JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH ) ) {
59        return;
60    }
61
62    if ( is_404() ) {
63        if ( ! is_dir( Config::get_static_cache_dir_path() ) ) {
64            mkdir( Config::get_static_cache_dir_path(), 0775, true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
65        }
66        file_put_contents( Config::get_static_cache_dir_path() . '/404', '1' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
67        return true;
68    } else {
69        wp_delete_file( Config::get_static_cache_dir_path() . '/404' );
70        return false;
71    }
72}
73
74/**
75 * This ensures that the 404 tester is only run once per day, espicially for multisite.
76 */
77function jetpack_boost_404_tester_cron() {
78    // If we see it's been executed within 24 hours, don't run
79    if ( ! jetpack_boost_should_run_daily_network_cron_job( '404_tester' ) ) {
80        return;
81    }
82
83    jetpack_boost_404_tester();
84}
85
86/**
87 * This function is used to test if is_404() is working in wp-content/
88 * It sends a request to a non-existent URL, that will execute the 404 handler
89 * in jetpack_boost_check_404_handler().
90 * Define the constant JETPACK_BOOST_DISABLE_404_TESTER to disable this.
91 * The constant JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH is the path to the file that will be requested.
92 *
93 * This function is called when the Minify_CSS or Minify_JS module is activated, and once per day.
94 */
95function jetpack_boost_404_tester() {
96    if ( defined( 'JETPACK_BOOST_DISABLE_404_TESTER' ) && JETPACK_BOOST_DISABLE_404_TESTER ) {
97        return;
98    }
99
100    $minification_enabled = '';
101    wp_remote_get( home_url( JETPACK_BOOST_STATIC_CACHE_404_TESTER_PATH ) );
102    if ( file_exists( Config::get_static_cache_dir_path() . '/404' ) ) {
103        wp_delete_file( Config::get_static_cache_dir_path() . '/404' );
104        $minification_enabled = 1;
105    } else {
106        $minification_enabled = 0;
107    }
108    update_site_option( 'jetpack_boost_static_minification', $minification_enabled );
109
110    return $minification_enabled;
111}
112
113add_action( 'jetpack_boost_404_tester_cron', 'jetpack_boost_404_tester_cron' );
114
115/**
116 * Setup the 404 tester.
117 *
118 * Schedule the 404 tester if the concatenation modules
119 * haven't been toggled since this feature was released.
120 * Only run this in wp-admin to avoid excessive updates to the option.
121 */
122function jetpack_boost_404_setup() {
123    // If we're on Atomic or Woa, don't setup the 404 tester.
124    if ( in_array( Boost_Admin_Config::get_hosting_provider(), array( 'atomic', 'woa' ), true ) ) {
125        return;
126    }
127
128    if ( is_admin() && get_site_option( 'jetpack_boost_static_minification', 'na' ) === 'na' ) {
129        update_site_option( 'jetpack_boost_static_minification', 0 ); // Add a default value if not set to avoid an extra SQL query.
130    }
131
132    jetpack_boost_page_optimize_schedule_404_tester();
133}
134
135/**
136 * This function is used to clean up the static cache folder.
137 * It removes files with the file extension passed in the $file_extension parameter.
138 *
139 * @param string $file_extension The file extension to clean up.
140 */
141function jetpack_boost_page_optimize_cleanup_cache( $file_extension ) {
142    $files = glob( Config::get_static_cache_dir_path() . "/*.min.{$file_extension}" );
143    foreach ( $files as $file ) {
144        wp_delete_file( $file );
145    }
146}
147
148/**
149 * This function is used to clean up the static cache folder.
150 * It removes files that are stale and no longer needed.
151 * A file is considered stale if it's older than the files it depends on.
152 */
153function jetpack_boost_minify_remove_stale_static_files() {
154    $concat_files = glob( Config::get_static_cache_dir_path() . '/*.min.*' );
155    foreach ( $concat_files as $concat_file ) {
156        if ( ! file_exists( $concat_file ) ) {
157            continue;
158        }
159
160        $file_mtime = filemtime( $concat_file );
161        $file_parts = pathinfo( $concat_file );
162        $hash       = substr( $file_parts['basename'], 0, strpos( $file_parts['basename'], '.' ) );
163        $paths      = File_Paths::get( $hash );
164        if ( $paths ) {
165            $args = $paths->get_paths();
166            if ( ! is_array( $args ) ) {
167                continue;
168            }
169
170            // Get the site path relative to the webroot.
171            $site_url_path = wp_parse_url( site_url(), PHP_URL_PATH );
172            if ( ! $site_url_path ) {
173                $site_url_path = '';
174            }
175
176            // Get the webroot path by removing the site path from the ABSPATH. In case it's a subdirectory install, webroot is different from ABSPATH.
177            $webroot = substr( ABSPATH, 0, - strlen( $site_url_path ) - 1 );
178
179            foreach ( $args as $dependency_filename ) {
180                if ( ! file_exists( $webroot . $dependency_filename ) || filemtime( $webroot . $dependency_filename ) > $file_mtime ) {
181                    wp_delete_file( $concat_file ); // remove the file from the cache because it's stale.
182                }
183            }
184        }
185    }
186}
187
188function jetpack_boost_build_minify_output( $request_uri ) {
189    $jetpack_boost_page_optimize_types = jetpack_boost_page_optimize_types();
190
191    // Config
192    $concat_max_files = jetpack_boost_minify_concat_max_files();
193    $concat_unique    = true;
194
195    $file_parts = jetpack_boost_minify_get_file_parts( $request_uri );
196    // This route has only ever been given stored IDs, so it needs none of the older URL forms.
197    if ( ! $file_parts || ! File_Paths::is_id( $file_parts['file_name'] ) ) {
198        jetpack_boost_page_optimize_status_exit( 404 );
199    }
200
201    $file_paths = jetpack_boost_page_optimize_get_issued_list( $file_parts['file_name'] )->get_paths();
202
203    // file_paths contain something like array( '/foo/bar.css', '/foo1/bar/baz.css' )
204    if ( count( $file_paths ) > $concat_max_files ) {
205        jetpack_boost_page_optimize_status_exit( 400 );
206    }
207
208    jetpack_boost_page_optimize_check_files_size( $file_paths );
209
210    // If we're in a subdirectory context, use that as the root.
211    // We can't assume that the root serves the same content as the subdir.
212    $subdir_path_prefix = jetpack_boost_page_optimize_get_subdir_prefix( $request_uri );
213
214    $last_modified = 0;
215    $pre_output    = '';
216    $output        = '';
217    $total_bytes   = 0;
218    $limits        = jetpack_boost_page_optimize_limits();
219
220    $mime_type = '';
221
222    foreach ( $file_paths as $uri ) {
223        $fullpath = jetpack_boost_page_optimize_get_path( $uri );
224
225        if ( ! file_exists( $fullpath ) ) {
226            jetpack_boost_page_optimize_status_exit( 404 );
227        }
228
229        $mime_type = jetpack_boost_page_optimize_get_mime_type( $fullpath );
230        if ( ! in_array( $mime_type, $jetpack_boost_page_optimize_types, true ) ) {
231            jetpack_boost_page_optimize_status_exit( 400 );
232        }
233
234        if ( $concat_unique ) {
235            if ( ! isset( $last_mime_type ) ) {
236                $last_mime_type = $mime_type;
237            }
238
239            if ( $last_mime_type !== $mime_type ) {
240                jetpack_boost_page_optimize_status_exit( 400 );
241            }
242        }
243
244        // The web server serves the stored file by its extension, so that must match the list.
245        if ( $jetpack_boost_page_optimize_types[ $file_parts['file_extension'] ] !== $mime_type ) {
246            jetpack_boost_page_optimize_status_exit( 404 );
247        }
248
249        $stat = stat( $fullpath );
250        if ( false === $stat ) {
251            jetpack_boost_page_optimize_status_exit( 500 );
252        }
253
254        if ( $stat['mtime'] > $last_modified ) {
255            $last_modified = $stat['mtime'];
256        }
257
258        $total_bytes += $stat['size'];
259        if ( $total_bytes > $limits['files_read'] ) {
260            jetpack_boost_page_optimize_status_exit( 400 );
261        }
262
263        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
264        $buf = file_get_contents( $fullpath );
265        if ( false === $buf ) {
266            jetpack_boost_page_optimize_status_exit( 500 );
267        }
268
269        if ( 'text/css' === $mime_type ) {
270            $dirpath = jetpack_boost_strip_parent_path( $subdir_path_prefix, dirname( $uri ) );
271
272            // url(relative/path/to/file) -> url(/absolute/and/not/relative/path/to/file)
273            $buf = jetpack_boost_page_optimize_relative_path_replace( $buf, $dirpath );
274
275            // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
276            // This regex changes things like AlphaImageLoader(...src='relative/path/to/file'...) to AlphaImageLoader(...src='/absolute/path/to/file'...)
277            $buf = preg_replace(
278                '/(Microsoft.AlphaImageLoader\s*\([^\)]*src=(?:\'|")?)([^\/\'"\s\)](?:(?<!http:|https:).)*)\)/isU',
279                '$1' . ( $dirpath === '/' ? '/' : $dirpath . '/' ) . '$2)',
280                $buf
281            );
282
283            // The @charset rules must be on top of the output
284            if ( str_starts_with( $buf, '@charset' ) ) {
285                $buf = preg_replace_callback(
286                    '/(?P<charset_rule>@charset\s+[\'"][^\'"]+[\'"];)/i',
287                    function ( $match ) use ( &$pre_output ) {
288                        if ( str_starts_with( $pre_output, '@charset' ) ) {
289                            return '';
290                        }
291
292                        $pre_output = $match[0] . "\n" . $pre_output;
293
294                        return '';
295                    },
296                    $buf
297                );
298            }
299
300            // Move the @import rules on top of the concatenated output.
301            // Only @charset rule are allowed before them.
302            if ( str_contains( $buf, '@import' ) ) {
303                $buf = preg_replace_callback(
304                    '/(?P<pre_path>@import\s+(?:url\s*\()?[\'"\s]*)(?P<path>[^\'"\s](?:https?:\/\/.+\/?)?.+?)(?P<post_path>[\'"\s\)]*;)/i',
305                    function ( $match ) use ( $dirpath, &$pre_output ) {
306                        if ( ! str_starts_with( $match['path'], 'http' ) && '/' !== $match['path'][0] ) {
307                            $pre_output .= $match['pre_path'] . ( $dirpath === '/' ? '/' : $dirpath . '/' ) .
308                                            $match['path'] . $match['post_path'] . "\n";
309                        } else {
310                            $pre_output .= $match[0] . "\n";
311                        }
312
313                        return '';
314                    },
315                    $buf
316                );
317            }
318
319            jetpack_boost_page_optimize_check_output_size( strlen( $pre_output ) + strlen( $output ) + strlen( $buf ) );
320
321            // If filename indicates it's already minified, don't minify it again.
322            if ( ! jetpack_boost_page_optimize_is_already_minified( $fullpath ) ) {
323                // Minify CSS.
324                $buf = Minify::css( $buf );
325            }
326            $output .= "$buf";
327        } else {
328            // If filename indicates it's already minified, don't minify it again.
329            if ( ! jetpack_boost_page_optimize_is_already_minified( $fullpath ) ) {
330                // Minify JS
331                $buf = Minify::js( $buf );
332            }
333
334            $output .= "$buf;\n";
335        }
336
337        jetpack_boost_page_optimize_check_output_size( strlen( $pre_output ) + strlen( $output ) );
338    }
339
340    // Don't let trailing whitespace ruin everyone's day. Seems to get stripped by batcache
341    // resulting in ns_error_net_partial_transfer errors.
342    $output = rtrim( $output );
343
344    $headers = array(
345        'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $last_modified ) . ' GMT',
346        "Content-Type: $mime_type",
347    );
348
349    return array(
350        'headers' => $headers,
351        'content' => $pre_output . $output,
352    );
353}
354
355/**
356 * Get the file name and extension from the request URI.
357 *
358 * @param string $request_uri The request URI.
359 * @return array|false The file name and extension, or false if the request URI is invalid.
360 */
361function jetpack_boost_minify_get_file_parts( $request_uri ) {
362    $utils       = new Utils();
363    $request_uri = $utils->unslash( $request_uri );
364
365    $file_path = $utils->parse_url( $request_uri, PHP_URL_PATH );
366    if ( $file_path === false ) {
367        return false;
368    }
369
370    $file_info = pathinfo( $file_path );
371
372    $minify_path = $utils->parse_url( jetpack_boost_get_minify_url(), PHP_URL_PATH );
373    if ( trailingslashit( $file_info['dirname'] ) !== $minify_path ) {
374        return false;
375    }
376
377    $allowed_extensions = array_keys( jetpack_boost_page_optimize_types() );
378    if ( ! isset( $file_info['extension'] ) || ! in_array( $file_info['extension'], $allowed_extensions, true ) ) {
379        return false;
380    }
381
382    // Boost only links to <id>.min.<ext>, so any other name would rebuild on every request.
383    $file_name_parts = explode( '.', $file_info['basename'] );
384    $file_name       = $file_name_parts[0];
385    if ( $file_info['basename'] !== $file_name . '.min.' . $file_info['extension'] ) {
386        return false;
387    }
388
389    return array(
390        'file_name'      => $file_name,
391        'file_extension' => $file_info['extension'] ?? '',
392    );
393}