← Back
Editing: page-performance.php
<?php namespace GD_cORe\modules; define( 'GD_PAGE_PERF_DIR_URL', plugin_dir_url( __FILE__ ) ); define( 'GD_PAGE_PERF_DIR_PATH', plugin_dir_path( __FILE__ ) ); define( 'GD_PAGE_PERF_VERSION', 0.1 ); final class Page_Performance { /** * The plugin instance. * * @var Page_Performance */ private static $instance = null; /** * @var string mwp accountId */ private static $gdcore_mwp_account_id; /** * Required CAP to manage this plugin. */ const CAP = 'activate_plugins'; /** * REST API namespace. */ const REST_BASE = 'gd-page-perf'; /** * Page list column ID. */ const COLUMN_ID = 'gd_page_perf'; /** * Meta key used to cache results. */ const CACHE_META_KEY = 'gd_page_performance_result'; /** * Lighthouse constant */ const LIGHTHOUSE_SCORE_GOOD_THRESHOLD = 90; const LIGHTHOUSE_SCORE_OKAY_THRESHOLD = 50; /** * Page_Performance constructor. */ private function __construct() { add_action( 'init', [ $this, 'init' ] ); self::$gdcore_mwp_account_id = \GD_cORe_Site_Auth::account_id(); } /** * Initialize the script. * * @action init */ public function init() { if ( ! current_user_can( self::CAP ) ) { return; } add_action( 'admin_bar_menu', [ $this, 'admin_bar_menu' ], PHP_INT_MAX ); add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_scripts' ], 50 ); add_action( 'admin_init', [ $this, 'register_admin_scripts' ] ); // Post/Page list columns. add_action( 'manage_posts_columns', [ $this, 'register_columns' ] ); add_action( 'manage_pages_columns', [ $this, 'register_columns' ] ); add_action( 'manage_pages_custom_column', [ $this, 'render_column' ], 10, 2 ); add_action( 'manage_posts_custom_column', [ $this, 'render_column' ], 10, 2 ); // Rest endpoint used for caching. add_action( 'rest_api_init', [ $this, 'register_rest_endpoints' ] ); // Beaver Builder if ( class_exists( '\FLBuilder' ) ) { add_filter( 'fl_builder_main_menu', function( $views ) { $views[ 'main' ][ 'items' ][ 33 ] = array( 'label' => 'Enable Page Performance', // i18n 'type' => 'event', 'eventName' => 'togglePagePerf', ); return $views; }); } } /** * Admin bar menu. * * @action admin_bar_menu * * @param \WP_Admin_Bar $admin_bar */ public function admin_bar_menu( \WP_Admin_Bar $admin_bar ) { // Only show on front of site admin bar. if ( is_admin() ) { return; } $admin_bar->add_menu( [ 'id' => 'gd-core-page-performance', 'title' => '<span class="ab-icon dashicons dashicons-chart-line" style="cursor: pointer;"></span><span class="ab-label" style="cursor: pointer;">Page Performance</span>', 'parent' => 'top-secondary', 'href' => '', // Needed for onclick. 'meta' => [ 'onclick' => 'window.dispatchEvent( new Event( "toggleGDPagePerfEvent" ) ); return false;' ] ] ); } /** * Enqueue styles. * * @action admin_enqueue_scripts * @action wp_enqueue_scripts */ public function enqueue_scripts() { // Must be logged in if ( ! is_user_logged_in() ) return; // Must be editing a post global $post; if ( ! isset( $post->ID ) && ! is_admin() ) return; $default_asset_file = [ 'dependencies' => [], 'version' => GD_PAGE_PERF_VERSION, ]; $asset_filepath = GD_PAGE_PERF_DIR_PATH . '/build/main.asset.php'; $asset_file = file_exists( $asset_filepath ) ? include $asset_filepath : $default_asset_file; // Load main component script wp_enqueue_script( 'gd_page_perf', GD_PAGE_PERF_DIR_URL . 'build/main.js', $asset_file['dependencies'], $asset_file['version'], true ); // Beaver Builder if ( class_exists( '\FLBuilderModel' ) && \FLBuilderModel::is_builder_active() ) { wp_enqueue_script( 'gd_page_perf_init_bb', GD_PAGE_PERF_DIR_URL . 'scripts/bb-init.js', array(), '0.1' ); } // Expose variables to React component wp_localize_script( 'gd_page_perf', 'gdPagePerf', [ 'wpApiRoute' => sprintf('/%s/%d', self::REST_BASE, $post->ID ), 'cache' => $this->get_report_cache( $post->ID ), 'accountId' => self::$gdcore_mwp_account_id, 'adminPostUrl' => admin_url( 'admin-post.php' ), ] ); } public function register_admin_scripts() { global $pagenow; if ( 'edit.php' !== $pagenow ) { return; } wp_enqueue_script( 'wp-api-fetch' ); wp_enqueue_script( 'jquery' ); add_action( 'admin_print_scripts', [ $this, 'print_admin_scripts' ] ); wp_add_inline_style( 'edit', ' .fixed .column-gd_page_perf { width: 132px; } .wp-admin-page-perf { display: flex; flex-direction: column; } .wp-admin-page-perf__scores { display: flex; flex-direction: row; margin: 5px 0; } .wp-admin-page-perf__scores:hover .wp-admin-page-perf__score { opacity: 0.4; } .wp-admin-page-perf__score { margin-bottom: 0; transition: opacity 0.2s; } .wp-admin-page-perf__score:hover { opacity: 1 !important; } .wp-admin-page-perf__score a { display: flex; justify-content: center; align-items: center; line-height: 1; width: 25px; height: 25px; border: 2px solid green; border-radius: 50px; font-weight: 600; margin-right: 5px; } .wp-admin-page-perf__score:last-child a { margin-right: 0; } .wp-admin-page-perf__score a.is-good { border-color: #54a657; color: #54a657; } .wp-admin-page-perf__score a.is-okay { border-color: #ebae51; color: #ebae51; } .wp-admin-page-perf__score a.is-bad { border-color: #d91c2c; color: #d91c2c; } .wp-admin-page-perf__details { display: flex; flex-direction: row; justify-content: space-between; align-items: center; } .wp-admin-page-perf-button { border: none; margin: 0; padding: 0; background: none; color: #787c82; cursor: pointer; } .wp-admin-page-perf-button::after { content: "\f113"; background: none; color: #787c82; display: block; font: normal 16px/20px dashicons; speak: never; height: 20px; text-align: center; width: 20px; -webkit-font-smoothing: antialiased; transition: transform 0.2s; } .wp-admin-page-perf-button:hover::after { transform: rotate(-145deg); } .gd_page_perf .is-loading .wp-admin-page-perf-button::after { animation: wp-admin-page-perf-rotate 1.5s linear infinite; } .gd_page_perf .is-loading .wp-admin-page-perf-button:hover::after { transform: none; } @keyframes wp-admin-page-perf-rotate { to { transform: rotate(-360deg); } }' ); } public function print_admin_scripts() { ?> <script type='text/javascript'> var GD_TIME_FORMATTER = new Intl.RelativeTimeFormat( undefined, { numeric: 'auto', } ); var GD_TIME_DIVISIONS = [ { amount: 60, name: 'seconds' }, { amount: 60, name: 'minutes' }, { amount: 24, name: 'hours' }, { amount: 7, name: 'days' }, { amount: 4.34524, name: 'weeks' }, { amount: 12, name: 'months' }, { amount: Number.POSITIVE_INFINITY, name: 'years' }, ]; function gdFormatFetchTime( fetchTime ) { var duration = ( new Date( fetchTime ) - new Date() ) / 1000; for ( var i = 0; i < GD_TIME_DIVISIONS.length; i++ ) { var division = GD_TIME_DIVISIONS[ i ]; if ( Math.abs( duration ) < division.amount ) { return GD_TIME_FORMATTER.format( Math.round( duration ), division.name ); } duration /= division.amount; } }; function gdRequestPagePerformance(id) { var $elem = jQuery("#gd-page-perf-" + id); $elem.addClass("is-loading"); wp.apiFetch( { path: `<?php echo self::REST_BASE ?>/${id}?refresh=true&post_column=true`, method: "GET", } ).then( ( resp ) => { $elem.removeClass("is-loading"); $elem.html( resp ); } ).catch( () => { $elem.removeClass("is-loading"); } ); } </script> <?php } /** * Returns the page performance columns in the Post/Page list view. * @param array $columns * * @return array */ public function register_columns( array $columns ) { $columns[ self::COLUMN_ID ] = __( 'Page Performance', 'gd-core' ); return $columns; } /** * Render the page performance in the post page list view. * * @param string $column_id * @param int $post_id */ public function render_column( $column_id, $post_id ) { if ( $column_id !== self::COLUMN_ID ) { return; } $post = get_post( $post_id ); $refresh_button = " <button type='button' class='wp-admin-page-perf-button' onclick='gdRequestPagePerformance($post_id)' title='Refresh'> <span class='screen-reader-text'>Request a new Page Performance report.</span> </button> "; if ( $post->post_status !== 'publish' ) { echo "—"; return; } $report = $this->get_report_cache( $post->ID ); if ( ! $report ) { echo " <div id='gd-page-perf-$post_id' class='wp-admin-page-perf-empty'> $refresh_button </div> "; return; } printf( " <div id='gd-page-perf-%s' class='wp-admin-page-perf'> <ul class='wp-admin-page-perf__scores'> %s %s %s %s </ul> <div class='wp-admin-page-perf__details'> <span class='fetch-time' data-value='%s'></span> <script type='text/javascript'> var elem = jQuery('#gd-page-perf-%s .fetch-time'); var time = elem.data('value'); time = gdFormatFetchTime(time) elem.html(time); </script> %s </div> </div> ", $post_id, $this->render_column_score( $report['performance'], 'Performance', $report['reportId'] ), $this->render_column_score( $report['accessibility'], 'Accessibility', $report['reportId'] ), $this->render_column_score( $report['bestpractices'], 'Best Practices', $report['reportId'] ), $this->render_column_score( $report['seo'], 'SEO', $report['reportId'] ), $report['fetchTime'], $post_id, $refresh_button ); } /** * Render the page performance in the post page list view. * * @param int $score * @param string $label */ public function render_column_score( $score, $label, $reportId ) { switch ( $score ) { case ( $score >= self::LIGHTHOUSE_SCORE_GOOD_THRESHOLD ): $class = 'is-good'; break; case ( $score >= self::LIGHTHOUSE_SCORE_OKAY_THRESHOLD ): $class = 'is-okay'; break; default: $class = 'is-bad'; break; } $hash = strtolower( $label ); $hash = str_replace( ' ', '-', $hash ); $reportUrl = add_query_arg( [ 'action' => 'view_lighthouse_report', 'report_id' => $reportId, ], admin_url( 'admin-post.php' ) ); $reportUrl .= "#$hash"; return " <li class='wp-admin-page-perf__score'> <a href='$reportUrl' target='_blank' rel='noopener noreferrer' class='$class' title='$label'> $score </a> </li> "; } /** * Register REST endpoint used for caching the lighthouse response in the post meta. */ public function register_rest_endpoints() { register_rest_route( self::REST_BASE, '(?P<id>\d+)', [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_page_performance' ], 'permission_callback' => function() { return current_user_can( self::CAP ); }, 'args' => [ 'id' => [ 'type' => 'integer', 'validate_callback' => function( $param ) { return is_numeric( $param ); }, 'required' => true, ], ], ] ); } /** * Get page performance meta if it exist. * * @param array $request * * @return \WP_Error|\WP_HTTP_Response|\WP_REST_Response */ public function get_page_performance( $request ) { $post_id = (int) $request[ 'id' ]; if ( !! $request['refresh'] ) { $report = $this->refresh_lighthouse_report( $post_id ); if ( !! $request['post_column'] ) { ob_start(); $this->render_column( self::COLUMN_ID, $post_id); $report = ob_get_clean(); } return rest_ensure_response( $report ); } $meta = $this->get_report_cache( $post_id ); if ( empty( $meta ) ) { return rest_ensure_response( new \WP_Error( 'no_data', 'No data available', [ 'status' => 404 ] ) ); } return rest_ensure_response( $meta ); } /** * Fetch and refresh local cache of lighthouse report. * * @param int $post_id * * @return array|\WP_Error */ private function refresh_lighthouse_report( $post_id ) { $report_cache = $this->get_report_cache( $post_id ); if ( $report_cache && $report_cache[ 'status' ] === 'requested' ) { // Short circuit and ask for new status instead of asking for new report. return $this->refresh_incomplete_report( $report_cache, $post_id ); } $report = []; $url = $this->get_permalink( $post_id ); if ( empty( $url ) ) { return $this->error( 'error', 'Post does not have a URL' ); } $report_id = $this->request_report( $url ); if ( is_wp_error( $report_id ) ) { return $report_id; } $report[ 'reportId' ] = $report_id; $report[ 'status' ] = 'requested'; return $this->refresh_incomplete_report( $report, $post_id ); } /** * Takes in a incomplete report (report with status requested) and tries to fetch the complete set of data. * * @param array $report * @param int $post_id * * @return array|string|\WP_Error */ private function refresh_incomplete_report( $report, $post_id ) { $report_id = $report[ 'reportId' ]; /** * Check for report status to be processed before requesting the data. */ $status = $this->get_report_status( $report_id ); if ( is_wp_error( $status ) ) { return $status; } if ( $status !== 'processed' ) { return $this->error(); } /** * When the report is processed, we can fetch the full json report. */ $report_data = $this->get_report_data( $report_id ); // Nothing is saved unless the report data is readable. if ( is_wp_error( $report_data ) ) { return $report_data; } $report = $this->parse_report( $report, $report_data ); // Cache result per post_id. $this->update_report_cache( $post_id, $report ); return $report; } /** * Return the permalink of the post. * * @param int $post_id * * @return string|false */ private function get_permalink( $post_id ) { return get_permalink( $post_id ); } /** * Request a report from the pws API and return the report ID in the queue. * * @param string $url * * @return string|\WP_Error */ private function request_report( $url ) { if ( ! \GD_cORe_Site_Auth::is_scan_url( $url ) ) { return $this->error( 'invalid_scan_url', 'This URL cannot be scanned.' ); } // Report creation always goes through the signed Public API proxy. $request_body = wp_json_encode(['url' => $url]); $operation = \GD_cORe_Site_Auth::proxy_operation( 'POST', sprintf('lighthouse/reports?accountId=%s', self::$gdcore_mwp_account_id), $request_body ); if ( is_wp_error( $operation ) ) { return $operation; } $headers = [ 'Content-Type' => 'application/json', 'User-Agent' => 'GDCorePlugin/' . GD_cORe_VERSION, 'x-app-key' => 'wordpress-site' ]; $response = wp_remote_post( $operation['url'], [ 'body' => $request_body, 'headers' => array_merge($headers, $operation['headers']), 'timeout' => 30, 'sslverify' => true, 'redirection' => 0, ] ); if ( is_wp_error( $response ) ) { return $this->error('request_failed', 'Request to Lighthouse API failed', 500); } $status_error = $this->gdcore_status_error( $response ); if ( $status_error ) { // A 404 here means the route is unavailable, not a missing report. return $status_error->get_error_code() === 'report_not_found' ? $this->error( 'gdcore_unavailable', 'The Lighthouse service is temporarily unavailable', 503 ) : $status_error; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if ( isset($data['id']) && \GD_cORe_Site_Auth::is_report_id($data['id']) ) { return $data['id']; } return $this->error('report_request_failed', 'Failed to request Lighthouse report'); } /** * Ping the API in loop of 3 sec to get the status of the report. Max 19 attempts. * * @param string $report_id * * @return string|\WP_Error */ private function get_report_status( $report_id ) { if ( ! \GD_cORe_Site_Auth::is_report_id( $report_id ) ) { return $this->error( 'invalid_report_id', 'Invalid report ID' ); } $count = 0; do { $response = $this->get_report( $report_id, 'json' ); if ( is_wp_error( $response ) ) { return $response; } $status_error = $this->gdcore_status_error( $response ); if ( $status_error ) { return $status_error; } $data = json_decode( wp_remote_retrieve_body( $response ), true); $state = $data[ 0 ][ 'state' ] ?? null; if ( $state === 'processed' ) { return 'processed'; } // A malformed body is not a GDCore state, so it is not terminal. if ( ! is_string( $state ) ) { return $this->error( 'gdcore_unavailable', 'The Lighthouse service is temporarily unavailable', 503 ); } if ( $state !== 'requested' ) { return $this->error( 'report_failed', 'Report could not be completed. A new scan may be required.' ); } sleep( 3 ); $count++; } while ( $count < 19 ); return 'requested'; } /** * Get the full report once we know it was processed by the API. * * @param string $report_id * * @return array|\WP_Error */ private function get_report_data( $report_id ) { if ( ! \GD_cORe_Site_Auth::is_report_id( $report_id ) ) { return $this->error( 'invalid_report_id', 'Invalid report ID' ); } $response = $this->get_report( $report_id, 'reportJson' ); if ( is_wp_error( $response ) ) { return $this->error(); } $status_error = $this->gdcore_status_error( $response ); if ( $status_error ) { return $status_error; } $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $data ) ) { return $this->error( 'invalid_report', 'Invalid report data' ); } return $data; } /** * Fetch a report in the given format through the signed Public API proxy, * so it is read from the same GDCore environment that created it. * * @param string $report_id Validated report ID. * @param string $format * * @return array|\WP_Error */ private function get_report( $report_id, $format ) { $operation = \GD_cORe_Site_Auth::proxy_operation( 'GET', sprintf( 'lighthouse/reports/%s?format=%s', $report_id, $format ) ); if ( is_wp_error( $operation ) ) { return $operation; } $headers = [ 'User-Agent' => 'GDCorePlugin/' . GD_cORe_VERSION, 'x-app-key' => 'wordpress-site', ]; $response = wp_remote_get( $operation['url'], [ 'headers' => array_merge( $headers, $operation['headers'] ), 'timeout' => 15, 'sslverify' => true, 'redirection' => 0, ] ); // Never propagate transport diagnostics. return is_wp_error( $response ) ? $this->error( 'gdcore_unavailable', 'The Lighthouse service is temporarily unavailable', 503 ) : $response; } /** * Map GDCore auth/availability failures to errors that do not echo the * upstream body. * * @param array $response * * @return \WP_Error|null */ private function gdcore_status_error( $response ) { $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status === 401 || $status === 403 ) { return $this->error( 'gdcore_unauthorized', 'This site could not be authorized with the Lighthouse service', 502 ); } if ( $status === 404 ) { return $this->error( 'report_not_found', 'Report not found. A new scan may be required.', 404 ); } if ( $status === 429 ) { return $this->error( 'quota_exceeded', 'Report limit reached.', 429 ); } if ( $status === 503 ) { return $this->error( 'gdcore_unavailable', 'The Lighthouse service is temporarily unavailable', 503 ); } if ( $status < 200 || $status >= 300 ) { return $this->error( 'gdcore_unavailable', 'The Lighthouse service is temporarily unavailable', 503 ); } return null; } /** * Parse the lighthouse report for storage. * * @param array $report * @param array $data * * @return array */ private function parse_report( $report, $data ) { // Null or missing values (Lighthouse reports null for checks that could // not run) count as 0, as before, rather than failing the report. $number = function ( $value ) { return is_numeric( $value ) ? (float) $value : 0.0; }; $report[ 'status' ] = 'processed'; $report[ 'performance' ] = round( $number( $data[ 'categories' ][ 'performance' ][ 'score' ] ?? null ) * 100 ); $report[ 'accessibility' ] = round( $number( $data[ 'categories' ][ 'accessibility' ][ 'score' ] ?? null ) * 100 ); $report[ 'bestpractices' ] = round( $number( $data[ 'categories' ][ 'best-practices' ][ 'score' ] ?? null ) * 100 ); $report[ 'seo' ] = round( $number( $data[ 'categories' ][ 'seo' ][ 'score' ] ?? null ) * 100 ); $report[ 'fcp' ] = round( ( round( $number( $data[ 'audits' ][ 'first-contentful-paint' ][ 'numericValue' ] ?? null ) ) / 1000 ) * 10 ) / 10; $report[ 'speed' ] = round( ( round( $number( $data[ 'audits' ][ 'speed-index' ][ 'numericValue' ] ?? null ) ) / 1000 ) * 10 ) / 10; $report[ 'fetchTime' ] = $data['fetchTime'] ?? null; return $report; } /** * Update the page performance data for faster access. */ private function update_report_cache( $post_id, $report ) { update_post_meta( $post_id, self::CACHE_META_KEY, $report ); } /** * Return the cache report for the current post id. * * @param int $post_id */ private function get_report_cache( $post_id ) { return get_post_meta( (int) $post_id, self::CACHE_META_KEY, true ); } /** * Return new error. Mainly use in API response for state management. * * @param string $code * @param string $message * @param int $status * * @return \WP_Error */ private function error( $code = 'error', $message = 'Something went wrong', $status = 500 ) { return new \WP_Error( $code, $message, [ 'status' => $status ] ); } /** * Return the plugin instance. * * @return Page_Performance */ public static function load() { if ( ! self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Reset the plugin instance. */ public static function reset() { self::$instance = null; } } Page_Performance::load();
Save File
Cancel