> Tabelle => Schluessel. */ public static function parse_schema( $sql ) { $out = array(); if ( ! preg_match_all( '/CREATE TABLE\s+`?([A-Za-z0-9_$]+)`?\s*\((.*?)\)\s*(?:DEFAULT\s+)?(?:CHARACTER SET|COLLATE|ENGINE|;)/s', (string) $sql, $blocks, PREG_SET_ORDER ) ) { return $out; } foreach ( $blocks as $block ) { $table = $block[1]; $keys = array(); foreach ( preg_split( '/\R/', $block[2] ) as $line ) { $key = self::parse_key_line( $line ); if ( null !== $key ) { $keys[] = $key; } } $out[ $table ] = $keys; } return $out; } /** * Eine Zeile "KEY name (spalte(191),spalte2)" lesen; null, wenn es kein Schluessel ist. * * @param string $line * @return array{name:string,type:string,columns:string[],sql_columns:string[]}|null */ public static function parse_key_line( $line ) { if ( ! preg_match( '/^\s*(PRIMARY KEY|UNIQUE KEY|UNIQUE INDEX|KEY|INDEX)\s*([A-Za-z0-9_]*)\s*\(/i', $line, $m, PREG_OFFSET_CAPTURE ) ) { return null; } $kind = strtoupper( $m[1][0] ); $name = $m[2][0]; // Inhalt der ersten Klammer, auch mit verschachtelten Laengenangaben wie (191). $start = $m[0][1] + strlen( $m[0][0] ); $depth = 1; $end = $start; $len = strlen( $line ); while ( $end < $len && $depth > 0 ) { $char = $line[ $end ]; if ( '(' === $char ) { ++$depth; } elseif ( ')' === $char ) { --$depth; } ++$end; } if ( 0 !== $depth ) { return null; } $inner = substr( $line, $start, $end - 1 - $start ); $sql_columns = array(); $columns = array(); $piece = ''; $level = 0; foreach ( str_split( $inner . ',' ) as $char ) { if ( ',' === $char && 0 === $level ) { $piece = trim( $piece ); if ( '' !== $piece ) { $sql_columns[] = $piece; $columns[] = strtolower( (string) preg_replace( '/\(.*$/', '', trim( $piece, '` ' ) ) ); } $piece = ''; continue; } $level += '(' === $char ? 1 : ( ')' === $char ? -1 : 0 ); $piece .= $char; } if ( array() === $columns ) { return null; } $type = 'PRIMARY KEY' === $kind ? 'primary' : ( 0 === strpos( $kind, 'UNIQUE' ) ? 'unique' : 'index' ); return array( 'name' => 'primary' === $type ? 'PRIMARY' : $name, 'type' => $type, 'columns' => $columns, 'sql_columns' => $sql_columns, ); } /** * Vorhandene Indizes einer Tabelle aus den Zeilen von SHOW INDEX. * * @param array> $rows * @return array Name => Index, Spalten in der Reihenfolge des Index. */ public static function group_indexes( array $rows ) { $tmp = array(); foreach ( $rows as $row ) { $name = isset( $row['Key_name'] ) ? (string) $row['Key_name'] : ''; if ( '' === $name ) { continue; } if ( ! isset( $tmp[ $name ] ) ) { $tmp[ $name ] = array( 'unique' => isset( $row['Non_unique'] ) && 0 === (int) $row['Non_unique'], 'fulltext' => isset( $row['Index_type'] ) && 'FULLTEXT' === strtoupper( (string) $row['Index_type'] ), 'cols' => array(), ); } $tmp[ $name ]['cols'][ isset( $row['Seq_in_index'] ) ? (int) $row['Seq_in_index'] : count( $tmp[ $name ]['cols'] ) + 1 ] = strtolower( isset( $row['Column_name'] ) ? (string) $row['Column_name'] : '' ); } $out = array(); foreach ( $tmp as $name => $index ) { ksort( $index['cols'] ); $out[ $name ] = array( 'unique' => $index['unique'], 'fulltext' => $index['fulltext'], 'columns' => array_values( $index['cols'] ), ); } return $out; } /** * Welche erwarteten Schluessel fehlen? Verglichen werden die Spalten, nicht der Name: Ein Index mit anderem * Namen, aber denselben ersten Spalten deckt den erwarteten ab (so bleiben von anderen Werkzeugen * umbenannte Indizes unbeanstandet). Primaer- und eindeutige Schluessel muessen genau diese Spalten haben. * * @param array $expected * @param array $existing * @return array */ public static function missing_keys( array $expected, array $existing ) { $missing = array(); foreach ( $expected as $key ) { if ( ! self::is_covered( $key, $existing ) ) { $missing[] = $key; } } return $missing; } /** * @param array{name:string,type:string,columns:string[],sql_columns:string[]} $key * @param array $existing * @return bool */ private static function is_covered( array $key, array $existing ) { foreach ( $existing as $name => $index ) { if ( $index['fulltext'] ) { continue; } if ( 'primary' === $key['type'] ) { if ( 'PRIMARY' === $name && $index['columns'] === $key['columns'] ) { return true; } continue; } if ( 'unique' === $key['type'] ) { if ( $index['unique'] && $index['columns'] === $key['columns'] ) { return true; } continue; } if ( array_slice( $index['columns'], 0, count( $key['columns'] ) ) === $key['columns'] ) { return true; } } return false; } /** * Die Anweisung, die einen fehlenden Schluessel anlegt (nur zum Anzeigen, sie wird nie ausgefuehrt). * * @param string $table * @param array{name:string,type:string,columns:string[],sql_columns:string[]} $key * @return string '' wenn sich keine sichere Anweisung bilden laesst. */ public static function alter_statement( $table, array $key ) { $cols = array(); foreach ( $key['sql_columns'] as $column ) { if ( ! preg_match( '/^`?([A-Za-z0-9_]+)`?(\(\d+\))?$/', $column, $m ) ) { return ''; } $cols[] = '`' . $m[1] . '`' . ( isset( $m[2] ) ? $m[2] : '' ); } $list = implode( ', ', $cols ); if ( 'primary' === $key['type'] ) { return 'ALTER TABLE `' . $table . '` ADD PRIMARY KEY (' . $list . ');'; } return 'ALTER TABLE `' . $table . '` ADD ' . ( 'unique' === $key['type'] ? 'UNIQUE KEY' : 'KEY' ) . ' `' . $key['name'] . '` (' . $list . ');'; } /** * Befunde zu einer Tabelle. * * @param array $status Zeile aus SHOW TABLE STATUS (Engine, Collation, Data_length, Index_length, Data_free). * @param array $missing Fehlende Schluessel (aus missing_keys()), nur bei Tabellen von WordPress. * @return array}> code: missing_key, engine, charset, fragmented. */ public static function table_findings( array $status, array $missing ) { $findings = array(); $table = isset( $status['Name'] ) ? (string) $status['Name'] : ''; foreach ( $missing as $key ) { $findings[] = array( 'code' => 'missing_key', 'level' => 'warning', 'data' => array( 'key' => $key['name'], 'type' => $key['type'], 'columns' => implode( ', ', $key['columns'] ), 'statement' => self::alter_statement( $table, $key ), ), ); } $engine = isset( $status['Engine'] ) ? (string) $status['Engine'] : ''; if ( '' !== $engine && 'innodb' !== strtolower( $engine ) ) { $findings[] = array( 'code' => 'engine', 'level' => 'info', 'data' => array( 'engine' => $engine ), ); } $collation = isset( $status['Collation'] ) ? strtolower( (string) $status['Collation'] ) : ''; if ( '' !== $collation && 0 !== strpos( $collation, 'utf8mb4' ) ) { $findings[] = array( 'code' => 'charset', 'level' => 'info', 'data' => array( 'collation' => $collation ), ); } $free = isset( $status['Data_free'] ) ? (int) $status['Data_free'] : 0; $used = ( isset( $status['Data_length'] ) ? (int) $status['Data_length'] : 0 ) + ( isset( $status['Index_length'] ) ? (int) $status['Index_length'] : 0 ); if ( $free >= self::FRAGMENT_MIN_BYTES && $free >= $used * self::FRAGMENT_MIN_SHARE ) { $findings[] = array( 'code' => 'fragmented', 'level' => 'info', 'data' => array( 'free' => $free ), ); } return $findings; } /** * Der Befund fuer die Tabellen dieser Installation (liest die Datenbank, aendert nichts). * * @return array Tabellen mit Befunden zuerst. */ public static function report() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/schema.php'; $scope = is_multisite() ? 'blog' : 'all'; $expected = self::parse_schema( wp_get_db_schema( $scope ) ); $core = array_flip( array_values( $wpdb->tables( $scope ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Zustand der Tabellen lesen; ein Cache wuerde den Befund verfaelschen. $status = (array) $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A ); $prefix = is_multisite() ? $wpdb->get_blog_prefix() : $wpdb->prefix; $rows = array(); foreach ( $status as $row ) { $name = isset( $row['Name'] ) ? (string) $row['Name'] : ''; if ( '' === $name ) { continue; } $is_core = isset( $core[ $name ] ); // Weitere Tabellen (Plugins) mit dem Praefix der Website; auf Multisite nicht die Tabellen anderer Websites. if ( ! $is_core && ( 0 !== strpos( $name, $prefix ) || ( is_multisite() && preg_match( '/^' . preg_quote( $wpdb->base_prefix, '/' ) . '\d+_/', $name ) && 0 !== strpos( $name, $wpdb->get_blog_prefix() ) ) ) ) { continue; } $missing = array(); if ( $is_core && isset( $expected[ $name ] ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Der Tabellenname stammt aus $wpdb->tables(), %i maskiert ihn als Bezeichner. $index_rows = (array) $wpdb->get_results( $wpdb->prepare( 'SHOW INDEX FROM %i', $name ), ARRAY_A ); $missing = self::missing_keys( $expected[ $name ], self::group_indexes( $index_rows ) ); } $rows[] = array( 'name' => $name, 'core' => $is_core, 'engine' => isset( $row['Engine'] ) ? (string) $row['Engine'] : '', 'collation' => isset( $row['Collation'] ) ? (string) $row['Collation'] : '', 'rows' => isset( $row['Rows'] ) ? (int) $row['Rows'] : 0, 'data' => isset( $row['Data_length'] ) ? (int) $row['Data_length'] : 0, 'index' => isset( $row['Index_length'] ) ? (int) $row['Index_length'] : 0, 'findings' => self::table_findings( $row, $missing ), ); } usort( $rows, static function ( $a, $b ) { return count( $b['findings'] ) <=> count( $a['findings'] ) ?: ( $b['data'] + $b['index'] ) <=> ( $a['data'] + $a['index'] ); } ); return $rows; } }