Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
29.73% covered (danger)
29.73%
11 / 37
50.00% covered (danger)
50.00%
2 / 4
CRAP
n/a
0 / 0
wpcom_head_error_handler
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
wpcom_add_crossorigin_to_script_elements
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
wpcom_error_reporting_is_delegated
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_enqueue_error_reporting_script
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * Error reporting from wp-admin / Gutenberg context for Simple Sites and WoA.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8use Automattic\Jetpack\Jetpack_Mu_Wpcom;
9
10/**
11 * Inline  error handler that will capture errors before the main handler has a chance to.
12 *
13 * Errors are pushed to a global array called `_jsErr` which is then verified in the main handler.
14 *
15 * @see index.js
16 */
17function wpcom_head_error_handler() {
18    if ( wpcom_error_reporting_is_delegated() ) {
19        return;
20    }
21    ?><script type="text/javascript">
22        window._headJsErrorHandler = function( errEvent ) {
23            window._jsErr = window._jsErr || [];
24            window._jsErr.push( errEvent );
25        }
26        window.addEventListener( 'error', window._headJsErrorHandler );
27    </script>
28    <?php
29}
30
31/**
32 * Limit the attribute to script elements that point to scripts served from s0.wp.com.
33 *
34 * We might want to add stats.wp.com and widgets.wp.com here, too. See https://wp.me/pMz3w-cCq#comment-86959.
35 * "Staticized" (aka minified or concatenaded) scripts don't go through this pipeline, so they are not processed
36 * by this filter. The attribute is added to those directly in jsconcat, see D57238-code.
37 *
38 * @param string $tag String containing the def of a script tag.
39 */
40function wpcom_add_crossorigin_to_script_elements( $tag ) {
41    $end_of_tag = strpos( $tag, '>' );
42    if ( false === $end_of_tag ) {
43        return $tag;
44    }
45
46    /*
47     * Get JUST the <script ...> tag, not anything else. $tag can include the content of the script as well.
48     * Assumes that $tag begins with <script..., which does seem to be the case in our testing.
49     */
50    $script_tag = substr( $tag, 0, $end_of_tag + 1 );
51
52    // If the src of that script tag points to an internal domain, set crossorigin=anonymous.
53    if ( preg_match( '/<script.*src=.*(s0\.wp\.com|stats\.wp\.com|widgets\.wp\.com).*>/', $script_tag ) ) { // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript
54        // Update the src of the <script...> tag.
55        $new_tag = str_replace( ' src=', " crossorigin='anonymous' src=", $script_tag );
56
57        // Then, find the original script_tag within the ENTIRE $tag, and replace it with the updated version. Now the script includes crossorigin=anonymous.
58        return str_replace( $script_tag, $new_tag, $tag );
59    }
60
61    return $tag;
62}
63
64/**
65 * Whether the screen being rendered reports its own JavaScript errors.
66 *
67 * @return bool
68 */
69function wpcom_error_reporting_is_delegated() {
70    /**
71     * Filters whether this handler stands down because the screen reports for itself.
72     *
73     * An admin screen that sends its own errors to the JS error endpoint filters this to true,
74     * so a window error is not reported twice. ETK is detected by its script handle instead.
75     *
76     * @since $$next-version$$
77     *
78     * @param bool $delegated Whether another reporter owns the screen.
79     */
80    return (bool) apply_filters( 'wpcom_error_reporting_delegated', false );
81}
82
83/**
84 * Enqueue assets
85 */
86function wpcom_enqueue_error_reporting_script() {
87    // Bail if ETK has enqueued its script.
88    if ( wp_script_is( 'a8c-fse-error-reporting-script' ) ) {
89        return;
90    }
91
92    if ( wpcom_error_reporting_is_delegated() ) {
93        return;
94    }
95
96    $asset_file          = include Jetpack_Mu_Wpcom::BASE_DIR . 'build/error-reporting/error-reporting.asset.php';
97    $script_dependencies = $asset_file['dependencies'] ?? array();
98    $script_version      = $asset_file['version'] ?? filemtime( Jetpack_Mu_Wpcom::BASE_DIR . 'build/error-reporting/error-reporting.js' );
99
100    wp_enqueue_script(
101        'wpcom-error-reporting-script',
102        plugins_url( 'build/error-reporting/error-reporting.js', Jetpack_Mu_Wpcom::BASE_FILE ),
103        $script_dependencies,
104        $script_version,
105        true
106    );
107}
108
109/**
110 * Can be used to toggle the Error Reporting functionality.
111 *
112 * @param bool true if Error Reporting should be enabled, false otherwise.
113 */
114if ( apply_filters( 'a8c_enable_error_reporting', false ) ) {
115    add_action( 'admin_print_scripts', 'wpcom_head_error_handler', 0 );
116    add_filter( 'script_loader_tag', 'wpcom_add_crossorigin_to_script_elements', 99, 2 );
117
118    // We load as last as possible for performance reasons. The head handler will capture errors until the main handler is loaded.
119    add_action( 'admin_enqueue_scripts', 'wpcom_enqueue_error_reporting_script', 100 );
120}