*/ private static $sources = array(); /** @var array */ private static $wrapped = array(); /** @var list Kindzeiten der gerade laufenden Wrapper. */ private static $stack = array(); /** @var int */ private static $budget = self::WRAP_BUDGET; /** @var array */ private static $phase_times = array(); /** @var list */ private static $external = array(); /** @var list */ private static $http_open = array(); /** @var string */ private static $template = ''; /** @var array|null */ private static $roots = null; /** @var array */ private static $file_cache = array(); /** @var float */ private static $started = 0.0; /** @var bool Hat der Messkern SAVEQUERIES selbst gesetzt? */ private static $defined_savequeries = false; /** * Schaltet die Messung ein. Gibt es sie schon, passiert nichts. * * @param string $mode MODE_SELFCALL oder MODE_CAPTURE. * @param callable|null $sink Bekommt am Ende der Anfrage das Roh-Ergebnis. * @param bool $log_queries Abfragen sofort mitschreiben? (false: erst enable_query_log(), nachdem die Berechtigung geprueft ist.) */ public static function start( $mode, $sink = null, $log_queries = true ) { if ( '' !== self::$mode ) { return; } self::$mode = $mode; self::$sink = $sink; self::$started = microtime( true ); add_action( 'all', array( __CLASS__, 'on_all' ), PHP_INT_MIN ); if ( $log_queries ) { self::enable_query_log(); } add_filter( 'log_query_custom_data', array( __CLASS__, 'on_log_query' ), PHP_INT_MAX ); add_filter( 'template_include', array( __CLASS__, 'capture_template' ), PHP_INT_MAX ); add_filter( 'pre_http_request', array( __CLASS__, 'on_http_start' ), 1, 3 ); add_action( 'http_api_debug', array( __CLASS__, 'on_http_end' ), 10, 5 ); add_action( 'shutdown', array( __CLASS__, 'finish' ), PHP_INT_MAX ); } /** * Schreibt ab jetzt die Datenbankabfragen mit. wpdb prueft SAVEQUERIES bei * jeder Abfrage neu, die Konstante darf also auch spaeter noch gesetzt * werden (Abfragen davor fehlen in der Messung). Nur waehrend einer * ausdruecklich angeforderten und berechtigten Messung. */ public static function enable_query_log() { if ( '' !== self::$mode && ! defined( 'SAVEQUERIES' ) ) { self::$defined_savequeries = true; define( 'SAVEQUERIES', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Konstante von WordPress selbst. } } /** * Schaltet die Messung ab (z. B. wenn der Besitzer des Cookies doch kein * Administrator ist). Die schon verpackten Callbacks bleiben stehen, rufen * aber nur noch das Original auf und verbuchen nichts mehr. */ public static function stop() { if ( '' === self::$mode ) { return; } self::$mode = ''; self::$sink = null; remove_action( 'all', array( __CLASS__, 'on_all' ), PHP_INT_MIN ); remove_filter( 'log_query_custom_data', array( __CLASS__, 'on_log_query' ), PHP_INT_MAX ); remove_filter( 'template_include', array( __CLASS__, 'capture_template' ), PHP_INT_MAX ); remove_filter( 'pre_http_request', array( __CLASS__, 'on_http_start' ), 1 ); remove_action( 'http_api_debug', array( __CLASS__, 'on_http_end' ), 10 ); remove_action( 'shutdown', array( __CLASS__, 'finish' ), PHP_INT_MAX ); } /** * Hat der Messkern die Konstante SAVEQUERIES selbst gesetzt? Dann gehoert sie * nicht zur Einrichtung der Website (die Umgebung ignoriert sie). */ public static function defined_savequeries() { return self::$defined_savequeries; } public static function is_active() { return '' !== self::$mode; } public static function mode() { return self::$mode; } /** * Haken 'all': merkt Phasen, merkt die Template-Hierarchie nicht (nicht * noetig) und verpackt die Callbacks des gerade feuernden Hooks. */ public static function on_all() { if ( '' === self::$mode ) { return; } $hook = current_filter(); if ( in_array( $hook, self::PHASE_HOOKS, true ) && ! isset( self::$phase_times[ $hook ] ) ) { self::$phase_times[ $hook ] = microtime( true ); } if ( self::$budget <= 0 || empty( $GLOBALS['wp_filter'][ $hook ] ) ) { return; } $wp_hook = $GLOBALS['wp_filter'][ $hook ]; if ( ! ( $wp_hook instanceof WP_Hook ) ) { return; } foreach ( $wp_hook->callbacks as $priority => &$callbacks ) { foreach ( $callbacks as $id => &$callback ) { if ( self::$budget <= 0 ) { break 2; } $key = $hook . "\0" . $priority . "\0" . $id; if ( isset( self::$wrapped[ $key ] ) ) { continue; } self::$wrapped[ $key ] = true; --self::$budget; $original = $callback['function']; $ref = self::reflect_callback( $original ); // Callbacks mit Referenz-Parametern duerfen nicht ueber // call_user_func_array() laufen (in PHP 8 ein Fatal Error). // Sie bleiben unveraendert und damit ungemessen. if ( self::has_by_ref_param( $ref ) ) { continue; } $callback['function'] = self::make_wrapper( $original, self::source_of_reflection( $ref ) ); } unset( $callback ); } unset( $callbacks ); } /** * @param callable $original * @param array{type:string,name:string,key:string} $source * @return Closure */ private static function make_wrapper( $original, array $source ) { return static function () use ( $original, $source ) { $args = func_get_args(); if ( '' === self::$mode ) { return call_user_func_array( $original, $args ); } self::$stack[] = 0.0; $start = microtime( true ); try { return call_user_func_array( $original, $args ); } finally { $elapsed = microtime( true ) - $start; $children = (float) array_pop( self::$stack ); $exclusive = max( 0.0, $elapsed - $children ); if ( self::$stack ) { self::$stack[ count( self::$stack ) - 1 ] += $elapsed; } self::record( $source, $exclusive ); } }; } /** * @param array{type:string,name:string,key:string} $source */ private static function record( array $source, $seconds ) { $key = $source['key']; if ( ! isset( self::$sources[ $key ] ) ) { self::$sources[ $key ] = array( 'type' => $source['type'], 'name' => $source['name'], 'ms' => 0.0, 'calls' => 0, ); } self::$sources[ $key ]['ms'] += $seconds * 1000; self::$sources[ $key ]['calls'] += 1; } /** * Haken log_query_custom_data: schreibt die Herkunft in den Datensatz der Abfrage. */ public static function on_log_query( $query_data ) { if ( '' === self::$mode ) { return $query_data; } if ( ! is_array( $query_data ) ) { $query_data = array(); } $query_data['wp360_so_source'] = self::resolve_backtrace_source()['key']; return $query_data; } public static function capture_template( $template ) { if ( '' !== self::$mode && is_string( $template ) ) { self::$template = $template; } return $template; } /** * Haken pre_http_request: merkt Start und Verursacher eines externen Aufrufs. * Gibt den Eingangswert unveraendert zurueck. */ public static function on_http_start( $preempt, $args = array(), $url = '' ) { if ( '' !== self::$mode && is_string( $url ) ) { self::$http_open[] = array( 'url' => $url, 'start' => microtime( true ), 'source' => self::resolve_backtrace_source()['key'], ); } return $preempt; } /** * Haken http_api_debug: Ende eines externen Aufrufs. */ public static function on_http_end( $response = null, $context = '', $class = '', $args = array(), $url = '' ) { if ( '' === self::$mode || 'response' !== $context ) { return; } for ( $i = count( self::$http_open ) - 1; $i >= 0; $i-- ) { if ( self::$http_open[ $i ]['url'] !== $url ) { continue; } $open = self::$http_open[ $i ]; array_splice( self::$http_open, $i, 1 ); $host = parse_url( (string) $url, PHP_URL_HOST ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url if ( is_string( $host ) && '' !== $host && count( self::$external ) < 50 ) { self::$external[] = array( 'host' => $host, 'ms' => round( ( microtime( true ) - $open['start'] ) * 1000, 2 ), 'source' => $open['source'], ); } return; } } /** * Haken shutdown (zuletzt): baut das Roh-Ergebnis und gibt es weiter. */ public static function finish() { if ( '' === self::$mode ) { return; } $sink = self::$sink; $raw = self::result(); self::stop(); if ( is_callable( $sink ) ) { call_user_func( $sink, $raw ); } } /** * Roh-Ergebnis der Messung (Eingabe fuer Measurement::normalize()). * * @return array */ public static function result() { $now = microtime( true ); $begin = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? (float) $_SERVER['REQUEST_TIME_FLOAT'] : self::$started; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput $origin = 'frontend'; if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) { $origin = 'ajax'; } elseif ( function_exists( 'is_admin' ) && is_admin() ) { $origin = 'backend'; } $sources = array(); foreach ( self::$sources as $row ) { $sources[] = array( 'type' => $row['type'], 'name' => $row['name'], 'ms' => round( $row['ms'], 2 ), ); } $notes = array(); // Alles, was vor diesem Plugin geladen wurde, ist nicht erfasst. $notes[] = 'before_doctor_not_measured'; // SAVEQUERIES steht schon vor uns auf false (wp-config.php): es gibt keine Abfragedaten. if ( defined( 'SAVEQUERIES' ) && ! SAVEQUERIES && ! self::$defined_savequeries ) { $notes[] = 'queries_not_logged'; } $result = array( 'origin' => $origin, // Nur Pfad und Namen der Parameter: Werte (auch der Messschluessel) bleiben draussen. 'url' => Wp360_Speed_Optimizer_Doctor_Measurement::clean_url( isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput 'time' => time(), 'server_ms' => round( ( $now - $begin ) * 1000, 2 ), 'memory_peak' => memory_get_peak_usage(), 'memory_limit' => Wp360_Speed_Optimizer_Doctor_Environment::memory_limit(), 'template' => self::relative_template(), 'queries' => self::query_summary(), 'sources' => $sources, 'phases' => self::phases( $begin ), 'external' => self::$external, 'notes' => $notes, ); return $result; } /** * @return array */ private static function phases( $begin ) { $phases = array(); $prev = $begin; foreach ( self::PHASE_HOOKS as $hook ) { if ( ! isset( self::$phase_times[ $hook ] ) ) { continue; } $phases[ $hook ] = round( max( 0.0, self::$phase_times[ $hook ] - $prev ) * 1000, 2 ); $prev = self::$phase_times[ $hook ]; } return $phases; } /** * Zusammenfassung aus wpdb::$queries: Anzahl, Zeit, langsamste, doppelte, * je Quelle. Die Texte werden vor dem Weitergeben entschaerft. * * @return array */ private static function query_summary() { global $wpdb; $summary = array( 'count' => 0, 'total_ms' => 0.0, 'slowest' => array(), 'duplicates' => array(), 'by_source' => array(), ); if ( empty( $wpdb->queries ) || ! is_array( $wpdb->queries ) ) { return $summary; } // Unter NO_BACKSLASH_ESCAPES gilt der Backslash nicht als Maskierung. $backslash = true; if ( ! empty( $wpdb->dbh ) ) { $mode = $wpdb->get_var( 'SELECT @@sql_mode' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery if ( is_string( $mode ) && false !== stripos( $mode, 'NO_BACKSLASH_ESCAPES' ) ) { $backslash = false; } } $rows = array_slice( $wpdb->queries, 0, self::MAX_QUERIES ); $summary['count'] = count( $wpdb->queries ); $groups = array(); $by_source = array(); $all = array(); $total = 0.0; foreach ( $rows as $row ) { $sql = isset( $row[0] ) && is_string( $row[0] ) ? $row[0] : ''; $ms = isset( $row[1] ) ? (float) $row[1] * 1000 : 0.0; $source = isset( $row[4]['wp360_so_source'] ) ? (string) $row[4]['wp360_so_source'] : 'core'; $clean = Wp360_Speed_Optimizer_Doctor_Sql_Sanitizer::sanitize( $sql, Wp360_Speed_Optimizer_Doctor_Sql_Sanitizer::MAX_LENGTH, $backslash ); $total += $ms; $all[] = array( 'sql' => $clean, 'ms' => $ms, 'source' => $source, ); if ( '' !== $clean ) { if ( ! isset( $groups[ $clean ] ) ) { $groups[ $clean ] = array( 'sql' => $clean, 'count' => 0, 'ms' => 0.0, 'source' => $source, ); } ++$groups[ $clean ]['count']; $groups[ $clean ]['ms'] += $ms; } if ( ! isset( $by_source[ $source ] ) ) { list( $type, $name ) = array_pad( explode( ':', $source, 2 ), 2, '' ); $by_source[ $source ] = array( 'type' => $type, 'name' => $name, 'count' => 0, 'ms' => 0.0, ); } ++$by_source[ $source ]['count']; $by_source[ $source ]['ms'] += $ms; } usort( $all, static function ( $a, $b ) { return $b['ms'] <=> $a['ms']; } ); $duplicates = array(); foreach ( $groups as $group ) { if ( $group['count'] >= 2 ) { $duplicates[] = $group; } } usort( $duplicates, static function ( $a, $b ) { return $b['count'] <=> $a['count']; } ); $summary['total_ms'] = round( $total, 2 ); $summary['slowest'] = array_slice( $all, 0, 10 ); $summary['duplicates'] = array_slice( $duplicates, 0, 10 ); $summary['by_source'] = array_values( $by_source ); return $summary; } private static function relative_template() { if ( '' === self::$template ) { return ''; } $template = str_replace( '\\', '/', self::$template ); $root = str_replace( '\\', '/', trailingslashit( function_exists( 'get_theme_root' ) ? get_theme_root() : '' ) ); return '' !== $root && 0 === strpos( $template, $root ) ? substr( $template, strlen( $root ) ) : basename( $template ); } /** * Quelle aus dem Stack-Trace: der erste Aufrufer, der nicht zum Kern und * nicht zu diesem Plugin gehoert; sonst der Kern. * * @return array{type:string,name:string,key:string} */ private static function resolve_backtrace_source() { $trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 30 ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace foreach ( $trace as $frame ) { if ( empty( $frame['file'] ) ) { continue; } $source = self::classify_file( $frame['file'] ); if ( in_array( $source['type'], array( 'core', 'other' ), true ) ) { continue; } if ( self::is_own_plugin( $source ) ) { continue; } return $source; } return array( 'type' => 'core', 'name' => '', 'key' => 'core', ); } private static function is_own_plugin( array $source ) { return 'plugin' === $source['type'] && 0 === strpos( $source['name'], '360-orbit-speed-optimizer' ); } /** * @param ReflectionFunctionAbstract|null $ref * @return array{type:string,name:string,key:string} */ private static function source_of_reflection( $ref ) { $file = $ref ? $ref->getFileName() : false; if ( ! $file ) { return array( 'type' => 'other', 'name' => '', 'key' => 'other', ); } return self::classify_file( $file ); } /** * @return array{type:string,name:string,key:string} */ private static function classify_file( $file ) { if ( isset( self::$file_cache[ $file ] ) ) { return self::$file_cache[ $file ]; } if ( null === self::$roots ) { self::$roots = array( 'plugins' => defined( 'WP_PLUGIN_DIR' ) ? WP_PLUGIN_DIR : '', 'mu_plugins' => defined( 'WPMU_PLUGIN_DIR' ) ? WPMU_PLUGIN_DIR : '', 'themes' => function_exists( 'get_theme_root' ) ? get_theme_root() : '', 'abspath' => ABSPATH, ); } $source = Wp360_Speed_Optimizer_Doctor_Source_Classifier::classify( $file, self::$roots ); if ( count( self::$file_cache ) < 2000 ) { self::$file_cache[ $file ] = $source; } return $source; } /** * @param callable $callback * @return ReflectionFunctionAbstract|null */ private static function reflect_callback( $callback ) { try { if ( is_string( $callback ) && false !== strpos( $callback, '::' ) ) { $callback = explode( '::', $callback, 2 ); } if ( $callback instanceof Closure ) { return new ReflectionFunction( $callback ); } if ( is_array( $callback ) && isset( $callback[0], $callback[1] ) ) { return new ReflectionMethod( $callback[0], $callback[1] ); } if ( is_string( $callback ) && function_exists( $callback ) ) { return new ReflectionFunction( $callback ); } if ( is_object( $callback ) && method_exists( $callback, '__invoke' ) ) { return new ReflectionMethod( $callback, '__invoke' ); } } catch ( ReflectionException $e ) { return null; } return null; } /** * @param ReflectionFunctionAbstract|null $ref */ private static function has_by_ref_param( $ref ) { if ( ! $ref ) { return false; } foreach ( $ref->getParameters() as $param ) { if ( $param->isPassedByReference() ) { return true; } } return false; } }