array( version removed, what to use instead ). */ const PHP_REMOVED = array( 'create_function' => array( '8.0', 'an anonymous function' ), 'each' => array( '8.0', 'a foreach loop' ), 'money_format' => array( '8.0', 'NumberFormatter' ), 'get_magic_quotes_gpc' => array( '8.0', 'nothing (it always returned false)' ), 'get_magic_quotes_runtime' => array( '8.0', 'nothing (it always returned false)' ), 'image2wbmp' => array( '8.0', 'imagewbmp()' ), 'read_exif_data' => array( '8.0', 'exif_read_data()' ), 'ereg' => array( '7.0', 'preg_match()' ), 'eregi' => array( '7.0', 'preg_match() with the i flag' ), 'ereg_replace' => array( '7.0', 'preg_replace()' ), 'eregi_replace' => array( '7.0', 'preg_replace() with the i flag' ), 'split' => array( '7.0', 'explode() or preg_split()' ), 'spliti' => array( '7.0', 'preg_split()' ), 'sql_regcase' => array( '7.0', 'preg_match() with the i flag' ), 'call_user_method' => array( '7.0', 'call_user_func()' ), 'call_user_method_array' => array( '7.0', 'call_user_func_array()' ), 'set_magic_quotes_runtime' => array( '7.0', 'nothing' ), ); /** Prefixes of whole removed extensions. */ const PHP_REMOVED_PREFIX = array( 'mysql_' => array( '7.0', 'the $wpdb object' ), 'mcrypt_' => array( '7.2', 'openssl_* or sodium_* functions' ), ); /** Deprecated in PHP (still work, show warnings, will be removed). */ const PHP_DEPRECATED = array( 'utf8_encode' => array( '8.2', 'mb_convert_encoding()' ), 'utf8_decode' => array( '8.2', 'mb_convert_encoding()' ), 'strftime' => array( '8.1', 'date(), wp_date() or IntlDateFormatter' ), 'gmstrftime' => array( '8.1', 'gmdate()' ), 'date_sunrise' => array( '8.1', 'date_sun_info()' ), 'date_sunset' => array( '8.1', 'date_sun_info()' ), 'mhash' => array( '8.1', 'hash()' ), 'libxml_disable_entity_loader' => array( '8.0', 'nothing (PHP 8 is safe by default)' ), ); /** Old WordPress functions: name => array( deprecated since, replacement ). */ const WP_DEPRECATED = array( 'get_page_by_title' => array( '6.2', 'WP_Query' ), 'wp_get_sites' => array( '4.6', 'get_sites()' ), 'get_currentuserinfo' => array( '4.5', 'wp_get_current_user()' ), 'like_escape' => array( '4.0', '$wpdb->esc_like()' ), 'screen_icon' => array( '3.8', 'nothing' ), 'wp_no_robots' => array( '5.7', 'wp_robots_no_robots()' ), 'get_theme_data' => array( '3.4', 'wp_get_theme()' ), 'wp_specialchars' => array( '2.8', 'esc_html()' ), 'attribute_escape' => array( '2.8', 'esc_attr()' ), 'js_escape' => array( '2.8', 'esc_js()' ), 'clean_url' => array( '3.0', 'esc_url()' ), 'get_usermeta' => array( '3.0', 'get_user_meta()' ), 'update_usermeta' => array( '3.0', 'update_user_meta()' ), 'delete_usermeta' => array( '3.0', 'delete_user_meta()' ), 'user_pass_ok' => array( '3.5', 'wp_authenticate()' ), 'get_settings' => array( '2.1', 'get_option()' ), 'the_editor' => array( '3.3', 'wp_editor()' ), 'register_sidebar_widget' => array( '2.8', 'wp_register_sidebar_widget()' ), 'unregister_sidebar_widget' => array( '2.8', 'wp_unregister_sidebar_widget()' ), 'add_custom_background' => array( '3.4', "add_theme_support( 'custom-background' )" ), 'add_custom_image_header' => array( '3.4', "add_theme_support( 'custom-header' )" ), 'get_userdatabylogin' => array( '3.3', "get_user_by( 'login', ... )" ), 'get_user_id_from_string' => array( '3.6', 'get_user_by()' ), 'wp_make_content_images_responsive' => array( '5.5', 'wp_filter_content_tags()' ), 'update_user_status' => array( '5.3', 'wp_update_user()' ), 'wp_get_http' => array( '4.4', 'the WP_Http class' ), 'get_the_author_ID' => array( '2.8', "get_the_author_meta( 'ID' )" ), ); public static function init() { register_shutdown_function( array( __CLASS__, 'on_shutdown' ) ); } /* --------------------------------------------------------------------- * Crash capture: remembers fatal errors that come from theme or plugin files. * ------------------------------------------------------------------ */ public static function on_shutdown() { $e = error_get_last(); if ( ! $e || ! in_array( $e['type'], array( E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ), true ) ) { return; } try { if ( ! function_exists( 'get_option' ) || ! function_exists( 'wp_normalize_path' ) ) { return; // WordPress itself is not loaded yet. } $file = wp_normalize_path( (string) $e['file'] ); $ours = false; foreach ( class_exists( 'Fixwise_Paths' ) ? Fixwise_Paths::quick_roots() : array() as $root ) { $ours = $ours || 0 === strpos( $file, $root ); } if ( ! $ours ) { return; // Only errors in plugin and theme code. } $log = get_option( self::FATALS, array() ); $log = is_array( $log ) ? $log : array(); $k = md5( $file . ':' . $e['line'] ); $log[ $k ] = array( 'file' => $file, 'line' => (int) $e['line'], 'message' => substr( (string) $e['message'], 0, 400 ), 'count' => isset( $log[ $k ] ) ? $log[ $k ]['count'] + 1 : 1, 'last' => time(), 'url' => isset( $_SERVER['REQUEST_URI'] ) ? substr( strtok( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), '?' ), 0, 200 ) : '', ); uasort( $log, function ( $a, $b ) { return $b['last'] - $a['last']; } ); update_option( self::FATALS, array_slice( $log, 0, 20, true ), false ); } catch ( Throwable $t ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- the site is already failing; never make it worse. } } /* --------------------------------------------------------------------- * What to check * ------------------------------------------------------------------ */ /** Active theme (and parent), active plugins and must-use plugins, each marked as from WordPress.org or not. */ public static function targets() { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $out = array(); $wthemes = get_site_transient( 'update_themes' ); $wplugs = get_site_transient( 'update_plugins' ); $in_wporg = function ( $t, $key ) { return is_object( $t ) && ( isset( $t->response[ $key ] ) || isset( $t->no_update[ $key ] ) ); }; $theme = wp_get_theme(); $seen = array(); foreach ( array( $theme, $theme->parent() ) as $t ) { if ( ! $t || ! $t->exists() || isset( $seen[ $t->get_stylesheet() ] ) ) { continue; } $seen[ $t->get_stylesheet() ] = 1; $out[] = array( 'type' => 'theme', 'slug' => $t->get_stylesheet(), 'name' => $t->get( 'Name' ), 'version' => $t->get( 'Version' ), 'dir' => wp_normalize_path( $t->get_stylesheet_directory() ), 'wporg' => $in_wporg( $wthemes, $t->get_stylesheet() ), ); } foreach ( get_plugins() as $file => $p ) { if ( ! is_plugin_active( $file ) || 0 === strpos( $file, 'fixwise/' ) ) { continue; } $dir = dirname( $file ); $out[] = array( 'type' => 'plugin', 'slug' => '.' === $dir ? basename( $file, '.php' ) : $dir, 'file' => $file, 'name' => $p['Name'], 'version' => $p['Version'], 'dir' => Fixwise_Paths::plugin( $file ), 'wporg' => $in_wporg( $wplugs, $file ), ); } if ( glob( Fixwise_Paths::mu_plugins() . '*.php' ) ) { $out[] = array( 'type' => 'mu', 'slug' => 'mu-plugins', 'name' => __( 'Must-use plugins', 'fixwise' ), 'version' => '', 'dir' => untrailingslashit( Fixwise_Paths::mu_plugins() ), 'wporg' => false, ); } return $out; } /** The theme/plugin a file belongs to, or null. */ private static function owner_of( $abs, $targets = null ) { $abs = wp_normalize_path( $abs ); foreach ( null === $targets ? self::targets() : $targets as $t ) { if ( $abs === $t['dir'] || 0 === strpos( $abs, rtrim( $t['dir'], '/' ) . '/' ) ) { return $t; } } // Inactive plugins and themes still count as "owned" for fix decisions. foreach ( array_merge( array( Fixwise_Paths::plugins() ), Fixwise_Paths::theme_roots() ) as $root ) { if ( 0 === strpos( $abs, $root ) ) { $slug = strtok( substr( $abs, strlen( $root ) ), '/' ); return array( 'type' => 'other', 'slug' => $slug, 'name' => $slug, 'dir' => $root . $slug, 'wporg' => true ); } } return null; } private static function rel( $abs ) { return Fixwise_Paths::short( $abs ); } /* --------------------------------------------------------------------- * Scan * ------------------------------------------------------------------ */ public static function scan() { $start = microtime( true ); $targets = self::targets(); $findings = array(); $notes = array(); $files = 0; $cut = false; foreach ( $targets as $t ) { if ( $t['wporg'] ) { continue; // WordPress.org code: checked against the official copy and its listing instead. } foreach ( self::php_files( $t['dir'] ) as $abs ) { if ( ++$files > self::MAX_FILES || microtime( true ) - $start > self::BUDGET ) { $cut = true; break 2; } foreach ( self::scan_file( $abs, $t ) as $f ) { $findings[] = $f; } } } if ( $cut ) { $notes[] = __( 'Large codebase: the check stopped after the time limit. Run it again to check more.', 'fixwise' ); } foreach ( $targets as $t ) { if ( 'theme' === $t['type'] && $t['wporg'] ) { $f = self::theme_integrity( $t ); if ( $f ) { $findings[] = $f; } } } foreach ( self::listing_checks( $targets ) as $f ) { $findings[] = $f; } $woo = self::woo_templates(); if ( $woo ) { $findings[] = $woo; } foreach ( self::errors( $targets ) as $f ) { $findings[] = $f; } // Most serious first; one list for the whole site. $rank = array( 'critical' => 0, 'warning' => 1, 'info' => 2 ); usort( $findings, function ( $a, $b ) use ( $rank ) { return array( $rank[ $a['severity'] ], $a['file'] ?? '', $a['line'] ?? 0 ) <=> array( $rank[ $b['severity'] ], $b['file'] ?? '', $b['line'] ?? 0 ); } ); $findings = array_slice( $findings, 0, 300 ); $result = array( 'scanned_at' => time(), 'files' => min( $files, self::MAX_FILES ), 'targets' => array_map( function ( $t ) { return array( 'name' => $t['name'], 'type' => $t['type'], 'wporg' => $t['wporg'], 'version' => $t['version'] ); }, $targets ), 'findings' => $findings, 'inactive' => self::inactive_themes(), 'notes' => $notes, ); update_option( self::LAST, $result, false ); return self::state(); } /** PHP files under a folder (or the file itself), skipping bundled libraries and tests. */ private static function php_files( $dir ) { if ( is_file( $dir ) ) { return array( $dir ); } if ( ! is_dir( $dir ) ) { return array(); } $out = array(); try { $it = new RecursiveIteratorIterator( new RecursiveCallbackFilterIterator( new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS ), function ( $f ) { if ( $f->isDir() ) { return ! in_array( strtolower( $f->getFilename() ), array( 'vendor', 'node_modules', 'tests', 'test', '.git', 'languages', 'assets' ), true ); } return 'php' === strtolower( $f->getExtension() ) && $f->getSize() < 1024 * 1024; } ) ); foreach ( $it as $f ) { $out[] = wp_normalize_path( $f->getPathname() ); if ( count( $out ) >= self::MAX_FILES ) { break; } } } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- unreadable folders are skipped. } sort( $out ); return $out; } private static function finding( $kind, $severity, $title, $detail, $extra = array() ) { $f = array_merge( array( 'kind' => $kind, 'severity' => $severity, 'title' => $title, 'detail' => $detail, 'file' => '', 'line' => 0, 'owner' => '', 'tier' => 'free', 'fixable' => false, 'items' => array(), ), $extra ); $f['id'] = substr( md5( $kind . '|' . $f['file'] . '|' . $f['line'] . '|' . $title . '|' . ( isset( $f['n'] ) ? $f['n'] : 0 ) ), 0, 12 ); unset( $f['n'] ); return $f; } /* --- One PHP file --- */ /** * Static checks on one file (nothing is run). Exposed for tests. * * @return array[] findings */ public static function scan_file( $abs, $target ) { $code = @file_get_contents( $abs ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, WordPress.WP.AlternativeFunctions if ( false === $code || '' === $code ) { return array(); } return self::scan_code( $code, self::rel( $abs ), $target ); } public static function scan_code( $code, $rel, $target ) { $out = array(); $owner = $target['name']; $base = array( 'file' => $rel, 'owner' => $owner, 'fixable' => empty( $target['wporg'] ), ); try { $tokens = token_get_all( $code, TOKEN_PARSE ); } catch ( ParseError $e ) { $out[] = self::finding( 'syntax', 'critical', __( 'Syntax error: this file cannot run', 'fixwise' ), /* translators: %s: PHP's error message. */ sprintf( __( 'PHP %1$s stops at this line: "%2$s". Any page that loads this file shows an error.', 'fixwise' ), PHP_VERSION, $e->getMessage() ), $base + array( 'line' => (int) $e->getLine() ) ); return $out; } catch ( Throwable $e ) { return $out; } $n = count( $tokens ); $per_rule = array(); $occ = array(); $add = function ( $rule, $severity, $title, $detail, $line, $tier = 'free' ) use ( &$out, &$per_rule, &$occ, $base ) { $per_rule[ $rule ] = isset( $per_rule[ $rule ] ) ? $per_rule[ $rule ] + 1 : 1; if ( $per_rule[ $rule ] > 5 ) { return; // Five per rule per file is enough to see the pattern. } $at = $rule . ':' . $line; $occ[ $at ] = isset( $occ[ $at ] ) ? $occ[ $at ] + 1 : 0; $out[] = self::finding( $rule, $severity, $title, $detail, $base + array( 'line' => (int) $line, 'tier' => $tier, 'n' => $occ[ $at ] ) ); }; $skip = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); $next = function ( $i ) use ( $tokens, $n, $skip ) { for ( $j = $i + 1; $j < $n; $j++ ) { if ( ! is_array( $tokens[ $j ] ) || ! in_array( $tokens[ $j ][0], $skip, true ) ) { return $j; } } return $n; }; $prev = function ( $i ) use ( $tokens, $skip ) { for ( $j = $i - 1; $j >= 0; $j-- ) { if ( ! is_array( $tokens[ $j ] ) || ! in_array( $tokens[ $j ][0], $skip, true ) ) { return $j; } } return -1; }; $not_call_before = array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_FUNCTION, T_NEW, T_CONST ); if ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) ) { $not_call_before[] = T_NULLSAFE_OBJECT_OPERATOR; } $name_tokens = array( T_STRING ); if ( defined( 'T_NAME_FULLY_QUALIFIED' ) ) { $name_tokens[] = T_NAME_FULLY_QUALIFIED; } for ( $i = 0; $i < $n; $i++ ) { $t = $tokens[ $i ]; if ( ! is_array( $t ) ) { continue; } list( $id, $text, $line ) = $t; // "${var}" inside strings: deprecated in PHP 8.2. if ( T_DOLLAR_OPEN_CURLY_BRACES === $id ) { $add( 'php_deprecated', version_compare( PHP_VERSION, '8.2', '>=' ) ? 'warning' : 'info', __( 'Old string syntax "${...}"', 'fixwise' ), __( 'PHP 8.2 deprecated "${variable}" inside strings and PHP 9 will remove it. Use "{$variable}" instead.', 'fixwise' ), $line ); continue; } if ( T_EVAL === $id ) { $add( 'eval', 'warning', __( 'eval() runs text as code', 'fixwise' ), __( 'If any part of that text can come from a visitor or the database, an attacker could run their own code on your server. It is also how most backdoors work.', 'fixwise' ), $line, 'pro' ); continue; } // Statements that print: echo / print / query( ... $_GET ... ) without prepare(). if ( T_VARIABLE === $id && '$wpdb' === $text ) { $a = $next( $i ); $b = $next( $a ); if ( $a < $n && is_array( $tokens[ $a ] ) && T_OBJECT_OPERATOR === $tokens[ $a ][0] && $b < $n && is_array( $tokens[ $b ] ) && in_array( strtolower( $tokens[ $b ][1] ), array( 'query', 'get_results', 'get_var', 'get_row', 'get_col' ), true ) ) { $args = self::call_args( $tokens, $next( $b ) ); if ( self::has_input( $args ) && ! self::has_sanitizer( $args, true ) ) { $add( 'sql_input', 'critical', __( 'Database query built from visitor input (SQL injection)', 'fixwise' ), __( 'Input from the address bar or a form goes straight into a database query. An attacker could read or change your whole database. Use $wpdb->prepare() with placeholders.', 'fixwise' ), $tokens[ $b ][2], 'pro' ); } } continue; } if ( ! in_array( $id, $name_tokens, true ) ) { continue; } $name = strtolower( ltrim( $text, '\\' ) ); $after = $next( $i ); $is_call = $after < $n && '(' === $tokens[ $after ]; $p = $prev( $i ); if ( $p >= 0 && is_array( $tokens[ $p ] ) && in_array( $tokens[ $p ][0], $not_call_before, true ) ) { continue; // A method, a declaration or a class name. } if ( ! $is_call ) { if ( 'filter_sanitize_string' === $name ) { $add( 'php_deprecated', version_compare( PHP_VERSION, '8.1', '>=' ) ? 'warning' : 'info', __( 'FILTER_SANITIZE_STRING is deprecated', 'fixwise' ), __( 'PHP 8.1 deprecated this filter. Use sanitize_text_field() or htmlspecialchars() instead.', 'fixwise' ), $line ); } continue; } if ( in_array( $name, array( 'unserialize', 'extract' ), true ) ) { $args = self::call_args( $tokens, $after ); if ( self::has_input( $args ) ) { if ( 'unserialize' === $name ) { $add( 'unserialize_input', 'critical', __( 'unserialize() on visitor input', 'fixwise' ), __( 'Unserialising data from a form, cookie or the address bar lets attackers create PHP objects and, with the wrong plugin installed, run code. Use json_decode() instead.', 'fixwise' ), $line, 'pro' ); } else { $add( 'extract_input', 'warning', __( 'extract() on visitor input', 'fixwise' ), __( 'This turns every field a visitor sends into a variable, so they can overwrite variables your code relies on. Read the fields you need one by one.', 'fixwise' ), $line, 'pro' ); } } continue; } $removed = null; if ( isset( self::PHP_REMOVED[ $name ] ) ) { $removed = self::PHP_REMOVED[ $name ]; } else { foreach ( self::PHP_REMOVED_PREFIX as $prefix => $info ) { if ( 0 === strpos( $name, $prefix ) ) { $removed = $info; break; } } } if ( $removed ) { if ( version_compare( PHP_VERSION, $removed[0], '>=' ) ) { if ( ! function_exists( $name ) ) { /* translators: 1: function, 2: PHP version, 3: replacement. */ $add( 'php_removed', 'critical', sprintf( __( '%s() no longer exists in PHP', 'fixwise' ), $name ), sprintf( __( '%1$s() was removed in PHP %2$s, and this server runs PHP %3$s. When this line runs, the page stops with a fatal error. Use %4$s instead.', 'fixwise' ), $name, $removed[0], PHP_VERSION, $removed[1] ), $line ); } } else { /* translators: 1: function, 2: PHP version, 3: replacement. */ $add( 'php_removed', 'warning', sprintf( __( '%1$s() breaks on PHP %2$s', 'fixwise' ), $name, $removed[0] ), sprintf( __( 'Your server runs PHP %1$s, where this still works. Hosts are moving to PHP %2$s, where it was removed and the page would stop with an error. Use %3$s instead.', 'fixwise' ), PHP_VERSION, $removed[0], $removed[1] ), $line ); } continue; } if ( isset( self::PHP_DEPRECATED[ $name ] ) ) { $d = self::PHP_DEPRECATED[ $name ]; /* translators: 1: function, 2: PHP version, 3: replacement. */ $add( 'php_deprecated', version_compare( PHP_VERSION, $d[0], '>=' ) ? 'warning' : 'info', sprintf( __( '%s() is deprecated in PHP', 'fixwise' ), $name ), sprintf( __( 'PHP %1$s deprecated %2$s(): it fills your error log with warnings and will be removed. Use %3$s instead.', 'fixwise' ), $d[0], $name, $d[1] ), $line ); continue; } if ( isset( self::WP_DEPRECATED[ $name ] ) ) { $d = self::WP_DEPRECATED[ $name ]; /* translators: 1: function, 2: WordPress version, 3: replacement. */ $add( 'wp_deprecated', 'info', sprintf( __( 'Old WordPress function %s()', 'fixwise' ), $name ), sprintf( __( 'WordPress replaced %1$s() in version %2$s. It still works for now but may be removed. Use %3$s instead.', 'fixwise' ), $name, $d[0], $d[1] ), $line ); } } return $out; } /** Tokens of one statement starting at $i (until ; or ?> at the same nesting level). */ private static function statement( $tokens, $i ) { $out = array(); $depth = 0; $n = count( $tokens ); for ( ; $i < $n && count( $out ) < 400; $i++ ) { $t = $tokens[ $i ]; if ( ! is_array( $t ) ) { if ( in_array( $t, array( '(', '[', '{' ), true ) ) { $depth++; } elseif ( in_array( $t, array( ')', ']', '}' ), true ) ) { $depth--; } elseif ( ';' === $t && $depth <= 0 ) { break; } } elseif ( T_CLOSE_TAG === $t[0] && $depth <= 0 ) { break; } elseif ( in_array( $t[0], array( T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES ), true ) ) { $depth++; } $out[] = $t; } return $out; } /** Tokens between the "(" at $i and its matching ")". */ private static function call_args( $tokens, $i ) { $out = array(); $n = count( $tokens ); if ( $i >= $n || '(' !== $tokens[ $i ] ) { return $out; } $depth = 0; for ( ; $i < $n && count( $out ) < 400; $i++ ) { $t = $tokens[ $i ]; if ( '(' === $t ) { $depth++; } elseif ( ')' === $t ) { $depth--; if ( 0 === $depth ) { break; } } $out[] = $t; } return $out; } /** Does this code use input a visitor controls? */ private static function has_input( $toks ) { $n = count( $toks ); for ( $i = 0; $i < $n; $i++ ) { $t = $toks[ $i ]; if ( ! is_array( $t ) || T_VARIABLE !== $t[0] ) { continue; } if ( in_array( $t[1], array( '$_GET', '$_POST', '$_REQUEST', '$_COOKIE' ), true ) ) { return true; } if ( '$_SERVER' === $t[1] ) { for ( $j = $i + 1; $j < min( $n, $i + 4 ); $j++ ) { if ( is_array( $toks[ $j ] ) && T_CONSTANT_ENCAPSED_STRING === $toks[ $j ][0] && preg_match( '/REQUEST_URI|PHP_SELF|HTTP_REFERER|QUERY_STRING|HTTP_USER_AGENT|HTTP_X_FORWARDED_FOR|PATH_INFO/', $toks[ $j ][1] ) ) { return true; } } } } return false; } /** Is the input escaped, sanitized or cast in the same statement? */ private static function has_sanitizer( $toks, $sql = false ) { $casts = array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ); foreach ( $toks as $t ) { if ( ! is_array( $t ) ) { continue; } if ( in_array( $t[0], $casts, true ) ) { return true; } if ( T_STRING === $t[0] ) { $f = strtolower( $t[1] ); if ( preg_match( '/^(esc_|sanitize_|wp_kses|absint$|intval$|floatval$|boolval$|htmlspecialchars$|htmlentities$|urlencode$|rawurlencode$|wp_json_encode$|json_encode$|number_format|count$|isset$|empty$|is_numeric$|in_array$|selected$|checked$|disabled$|wp_validate_redirect$|wp_strip_all_tags$|strip_tags$)/', $f ) ) { return true; } if ( $sql && in_array( $f, array( 'prepare', 'esc_sql', 'esc_like' ), true ) ) { return true; } } } return false; } /* --- WordPress.org theme: compare with the official copy --- */ private static function theme_integrity( $t ) { if ( ! class_exists( 'ZipArchive' ) || '' === (string) $t['version'] ) { return null; } $key = $t['slug'] . '@' . $t['version']; $cache = get_option( self::HASHES, array() ); $cache = is_array( $cache ) ? $cache : array(); if ( empty( $cache[ $key ] ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; $tmp = download_url( 'https://downloads.wordpress.org/theme/' . rawurlencode( $t['slug'] ) . '.' . rawurlencode( $t['version'] ) . '.zip', 60 ); if ( is_wp_error( $tmp ) ) { return null; // Not on WordPress.org at this version (or offline): nothing to compare. } $hashes = array(); $zip = new ZipArchive(); if ( true === $zip->open( $tmp ) ) { for ( $i = 0; $i < $zip->numFiles; $i++ ) { $name = $zip->getNameIndex( $i ); if ( '/' === substr( $name, -1 ) ) { continue; } $rel = preg_replace( '#^[^/]+/#', '', $name ); $hashes[ $rel ] = md5( (string) $zip->getFromIndex( $i ) ); } $zip->close(); } wp_delete_file( $tmp ); if ( ! $hashes ) { return null; } // Keep only the themes in use. $cache = array_filter( $cache, function ( $k ) use ( $t ) { return 0 !== strpos( $k, $t['slug'] . '@' ); }, ARRAY_FILTER_USE_KEY ); $cache[ $key ] = $hashes; update_option( self::HASHES, array_slice( $cache, -4, null, true ), false ); } $official = $cache[ $key ]; $changed = array(); $extra = array(); foreach ( $official as $rel => $md5 ) { // Only program files matter: WordPress's bundled copy of a default theme can differ from the // WordPress.org download in its readme and built CSS without anyone touching it. if ( ! preg_match( '/\.(php\d?|phtml)$/i', $rel ) ) { continue; } $abs = $t['dir'] . '/' . $rel; if ( is_file( $abs ) && md5_file( $abs ) !== $md5 ) { $changed[] = $rel; } } foreach ( self::php_files( $t['dir'] ) as $abs ) { $rel = substr( $abs, strlen( $t['dir'] ) + 1 ); if ( ! isset( $official[ $rel ] ) ) { $extra[] = $rel; } } if ( ! $changed && ! $extra ) { return null; } $items = array(); foreach ( array_slice( $changed, 0, 25 ) as $r ) { /* translators: %s: file path. */ $items[] = sprintf( __( 'Changed: %s', 'fixwise' ), $r ); } foreach ( array_slice( $extra, 0, 25 ) as $r ) { /* translators: %s: file path. */ $items[] = sprintf( __( 'Not in the official theme: %s', 'fixwise' ), $r ); } return self::finding( 'theme_modified', $extra ? 'critical' : 'warning', /* translators: %s: theme name. */ sprintf( __( '%s differs from the official WordPress.org copy', 'fixwise' ), $t['name'] ), $extra ? __( 'Extra PHP files inside a theme folder are a common sign of a hack. If you or your developer did not add them, run the malware scan and reinstall the theme. Customizations belong in a child theme.', 'fixwise' ) : __( 'Someone edited the theme\'s PHP files directly. The next theme update will undo those edits. If they are yours, move them into a child theme; if not, the theme may have been tampered with: reinstall it.', 'fixwise' ), array( 'owner' => $t['name'], 'items' => $items, 'link' => admin_url( 'themes.php' ) ) ); } /* --- Listing on WordPress.org: removed, or not updated for years --- */ private static function wporg_info( $type, $slug ) { $cache = get_transient( self::WPORG ); $cache = is_array( $cache ) ? $cache : array(); $k = $type . ':' . $slug; if ( ! array_key_exists( $k, $cache ) ) { $url = 'theme' === $type ? 'https://api.wordpress.org/themes/info/1.2/?action=theme_information&request[slug]=' . rawurlencode( $slug ) . '&request[fields][sections]=0' : 'https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slug]=' . rawurlencode( $slug ) . '&request[fields][sections]=0'; $res = wp_remote_get( $url, array( 'timeout' => 10 ) ); if ( is_wp_error( $res ) ) { return null; } $j = json_decode( wp_remote_retrieve_body( $res ), true ); $cache[ $k ] = is_array( $j ) ? array_intersect_key( $j, array_flip( array( 'closed', 'closed_date', 'reason_text', 'last_updated', 'error' ) ) ) : null; set_transient( self::WPORG, $cache, WEEK_IN_SECONDS ); } return $cache[ $k ]; } private static function listing_checks( $targets ) { $out = array(); $asked = 0; $start = microtime( true ); foreach ( $targets as $t ) { if ( ! $t['wporg'] || ! in_array( $t['type'], array( 'theme', 'plugin' ), true ) || ++$asked > 40 ) { continue; } if ( microtime( true ) - $start > 15 ) { break; // Answers are cached for a week, so the next scan carries on where this one stopped. } $info = self::wporg_info( $t['type'], $t['slug'] ); if ( ! $info ) { continue; } if ( ! empty( $info['closed'] ) ) { $out[] = self::finding( 'closed', 'critical', /* translators: %s: plugin or theme name. */ sprintf( __( '%s was removed from WordPress.org', 'fixwise' ), $t['name'] ), /* translators: %s: reason given by WordPress.org. */ sprintf( __( 'It gets no more updates. WordPress.org gave this reason: %s. Plugins are often closed for an unfixed security hole, so look for a replacement soon.', 'fixwise' ), ! empty( $info['reason_text'] ) ? $info['reason_text'] : __( 'not stated', 'fixwise' ) ), array( 'owner' => $t['name'] ) ); continue; } if ( ! empty( $info['last_updated'] ) ) { $ts = strtotime( $info['last_updated'] ); if ( $ts && $ts < time() - 2 * YEAR_IN_SECONDS ) { $years = floor( ( time() - $ts ) / YEAR_IN_SECONDS ); $out[] = self::finding( 'abandoned', 'warning', /* translators: 1: name, 2: number of years. */ sprintf( _n( '%1$s has not been updated for %2$d year', '%1$s has not been updated for %2$d years', $years, 'fixwise' ), $t['name'], $years ), __( 'Abandoned code stops getting security fixes and can break with new WordPress or PHP versions. Consider a maintained alternative.', 'fixwise' ), array( 'owner' => $t['name'] ) ); } } } return $out; } /* --- WooCommerce template overrides in the theme --- */ private static function woo_templates() { if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'WC' ) ) { return null; } if ( ! class_exists( 'WC_Admin_Status' ) ) { $f = WC()->plugin_path() . '/includes/admin/class-wc-admin-status.php'; if ( ! is_file( $f ) ) { return null; } include_once $f; } if ( ! is_callable( array( 'WC_Admin_Status', 'get_theme_overrides' ) ) ) { return null; } try { $o = WC_Admin_Status::get_theme_overrides(); } catch ( Throwable $e ) { return null; } $items = array(); foreach ( isset( $o['overrides'] ) ? (array) $o['overrides'] : array() as $ov ) { $ver = isset( $ov['version'] ) ? (string) $ov['version'] : ''; $core = isset( $ov['core_version'] ) ? (string) $ov['core_version'] : ''; if ( '' === $ver || ( $core && version_compare( $ver, $core, '<' ) ) ) { /* translators: 1: file, 2: theme copy version, 3: WooCommerce version. */ $items[] = sprintf( __( '%1$s (theme copy %2$s, WooCommerce %3$s)', 'fixwise' ), $ov['file'], '' === $ver ? '?' : $ver, $core ? $core : '?' ); } } if ( ! $items ) { return null; } return self::finding( 'woo_templates', 'warning', /* translators: %d: count. */ sprintf( _n( '%d outdated WooCommerce template in your theme', '%d outdated WooCommerce templates in your theme', count( $items ), 'fixwise' ), count( $items ) ), __( 'Your theme overrides these WooCommerce templates with older copies. That is a common cause of broken cart, checkout or account pages after a WooCommerce update. Ask the theme developer for an update, or update the copies in your child theme.', 'fixwise' ), array( 'items' => $items, 'tier' => 'woo', 'link' => admin_url( 'admin.php?page=wc-status' ) ) ); } /* --- PHP errors from theme and plugin files --- */ private static function debug_log_path() { return Fixwise_Paths::debug_log(); } private static function errors( $targets ) { $seen = array(); // 1. Crashes Fixwise caught itself. foreach ( (array) get_option( self::FATALS, array() ) as $e ) { if ( empty( $e['file'] ) ) { continue; } $seen[ $e['file'] . ':' . $e['line'] ] = array( 'type' => 'Fatal error', 'file' => $e['file'], 'line' => $e['line'], 'message' => $e['message'], 'count' => $e['count'], 'last' => $e['last'], ); } // 2. WordPress's debug log, if it is on (last 512 KB). $path = self::debug_log_path(); if ( $path && is_readable( $path ) ) { $size = filesize( $path ); $fh = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions if ( $fh ) { fseek( $fh, max( 0, $size - 512 * 1024 ) ); $tail = (string) fread( $fh, 512 * 1024 ); // phpcs:ignore WordPress.WP.AlternativeFunctions fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions if ( preg_match_all( '/^\[([^\]]+)\] PHP (Fatal error|Parse error|Warning|Notice|Deprecated):\s+(.*?) in (\S+?\.php)(?: on line |:)(\d+)/m', $tail, $m, PREG_SET_ORDER ) ) { foreach ( $m as $row ) { $file = wp_normalize_path( $row[4] ); $k = $file . ':' . $row[5]; if ( ! isset( $seen[ $k ] ) ) { $seen[ $k ] = array( 'type' => $row[2], 'file' => $file, 'line' => (int) $row[5], 'message' => substr( $row[3], 0, 400 ), 'count' => 0, 'last' => strtotime( $row[1] ) ?: 0 ); } $seen[ $k ]['count']++; $seen[ $k ]['last'] = max( $seen[ $k ]['last'], strtotime( $row[1] ) ?: 0 ); } } } } $own = wp_normalize_path( FIXWISE_DIR ); $out = array(); uasort( $seen, function ( $a, $b ) { return $b['count'] - $a['count']; } ); foreach ( $seen as $e ) { if ( ! Fixwise_Paths::in_code_roots( $e['file'] ) || 0 === strpos( wp_normalize_path( $e['file'] ), $own ) ) { continue; } $owner = self::owner_of( $e['file'], $targets ); $fatal = in_array( $e['type'], array( 'Fatal error', 'Parse error' ), true ); $out[] = self::finding( 'php_error', $fatal ? 'critical' : ( 'Warning' === $e['type'] ? 'warning' : 'info' ), /* translators: 1: error type, 2: theme or plugin name. */ sprintf( __( 'PHP %1$s in %2$s', 'fixwise' ), strtolower( $e['type'] ), $owner ? $owner['name'] : self::rel( $e['file'] ) ), /* translators: 1: message, 2: count. */ sprintf( _n( '"%1$s" (seen %2$d time, last %3$s).', '"%1$s" (seen %2$d times, last %3$s).', max( 1, $e['count'] ), 'fixwise' ), $e['message'], max( 1, $e['count'] ), $e['last'] ? human_time_diff( $e['last'] ) . ' ' . __( 'ago', 'fixwise' ) : __( 'unknown', 'fixwise' ) ), array( 'file' => self::rel( $e['file'] ), 'line' => (int) $e['line'], 'owner' => $owner ? $owner['name'] : '', 'tier' => 'pro', 'fixable' => $owner && empty( $owner['wporg'] ), ) ); if ( count( $out ) >= 25 ) { break; } } return $out; } /* --- Unused themes --- */ private static function inactive_themes() { $active = array( get_stylesheet(), get_template() ); $list = array(); $defaults = array(); foreach ( wp_get_themes() as $slug => $t ) { if ( in_array( $slug, $active, true ) ) { continue; } $list[ $slug ] = array( 'slug' => $slug, 'name' => $t->get( 'Name' ), 'version' => $t->get( 'Version' ), 'keep' => false ); if ( 0 === strpos( $slug, 'twenty' ) ) { $defaults[] = $slug; } } // Keep the newest default theme as a fallback, unless the active theme is a default theme. if ( $defaults && 0 !== strpos( get_template(), 'twenty' ) ) { usort( $defaults, function ( $a, $b ) { return version_compare( wp_get_theme( $b )->get( 'Version' ), wp_get_theme( $a )->get( 'Version' ) ) ?: strcmp( $b, $a ); } ); $list[ $defaults[0] ]['keep'] = true; } return array_values( $list ); } public static function delete_theme( $slug ) { if ( ! current_user_can( 'delete_themes' ) ) { return new WP_Error( 'forbidden', __( 'You are not allowed to delete themes.', 'fixwise' ), array( 'status' => 403 ) ); } $slug = (string) $slug; $row = null; foreach ( self::inactive_themes() as $t ) { if ( $t['slug'] === $slug ) { $row = $t; } } if ( ! $row ) { return new WP_Error( 'not_found', __( 'That theme is in use or no longer installed.', 'fixwise' ) ); } if ( $row['keep'] ) { return new WP_Error( 'keep', __( 'Fixwise keeps one default theme as a safe fallback.', 'fixwise' ) ); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/theme.php'; if ( 'direct' !== get_filesystem_method( array(), get_theme_root() ) ) { return new WP_Error( 'fs', __( 'Your server needs FTP details to delete files. Delete the theme in Appearance → Themes instead.', 'fixwise' ) ); } $res = delete_theme( $slug ); if ( true !== $res ) { return is_wp_error( $res ) ? $res : new WP_Error( 'failed', __( 'The theme could not be deleted. Try Appearance → Themes.', 'fixwise' ) ); } /* translators: %s: theme name. */ Fixwise_Log::add( 'code', sprintf( __( 'Deleted the unused theme %s.', 'fixwise' ), $row['name'] ) ); $last = get_option( self::LAST ); if ( is_array( $last ) ) { $last['inactive'] = self::inactive_themes(); update_option( self::LAST, $last, false ); } /* translators: %s: theme name. */ return array( 'message' => sprintf( __( '%s deleted.', 'fixwise' ), $row['name'] ), 'code' => self::state() ); } /* --------------------------------------------------------------------- * Health report summary line * ------------------------------------------------------------------ */ public static function health_check() { $r = self::scan(); $pro = Fixwise_License::has( 'code' ); $woo = Fixwise_License::has( 'woo' ); $visible = array_filter( $r['findings'], function ( $f ) use ( $pro, $woo ) { return 'free' === $f['tier'] || ( 'pro' === $f['tier'] && $pro ) || ( 'woo' === $f['tier'] && $woo ); } ); $crit = count( array_filter( $visible, function ( $f ) { return 'critical' === $f['severity']; } ) ); $warn = count( array_filter( $visible, function ( $f ) { return 'warning' === $f['severity']; } ) ); $hidden = count( $r['findings'] ) - count( $visible ); $status = $crit ? 'critical' : ( $warn ? 'warning' : 'good' ); if ( 'good' === $status ) { $title = __( 'Theme and plugin code looks fine', 'fixwise' ); } else { /* translators: %d: count. */ $title = sprintf( _n( '%d problem in your theme or plugin code', '%d problems in your theme or plugin code', $crit + $warn, 'fixwise' ), $crit + $warn ); } $detail = __( 'See "Theme & plugin code" above for each problem and where it is.', 'fixwise' ); if ( $hidden && ! $pro ) { /* translators: %d: count. */ $detail .= ' ' . sprintf( _n( 'Fixwise Pro found %d more risky-code or error item.', 'Fixwise Pro found %d more risky-code or error items.', $hidden, 'fixwise' ), $hidden ); } return array( 'id' => 'code_health', 'group' => 'security', 'status' => $status, 'title' => $title, 'detail' => 'good' === $status ? __( 'No syntax errors, PHP version problems, changed theme files or removed plugins found.', 'fixwise' ) : $detail, ); } /* --------------------------------------------------------------------- * State for the admin screen * ------------------------------------------------------------------ */ public static function state() { $r = get_option( self::LAST ); if ( ! is_array( $r ) ) { return null; } $fixes = (array) get_option( self::FIXES, array() ); foreach ( $r['findings'] as &$f ) { $f['has_fix'] = isset( $fixes[ $f['id'] ] ); } unset( $f ); return $r; } private static function find( $id ) { $r = get_option( self::LAST ); foreach ( is_array( $r ) ? $r['findings'] : array() as $f ) { if ( $f['id'] === $id ) { return $f; } } return null; } /* --------------------------------------------------------------------- * AI: explain & fix * ------------------------------------------------------------------ */ /** Full path of a finding's file ("plugins/…" or "themes/…"), read only. */ private static function abs_path( $rel ) { return Fixwise_Paths::from_short( $rel ); } public static function explain( $id ) { if ( ! Fixwise_License::has( 'code' ) ) { return new WP_Error( 'upgrade_required', __( 'AI explain & fix is part of Fixwise Pro.', 'fixwise' ) ); } $f = self::find( $id ); if ( ! $f || ! $f['file'] || ! $f['line'] ) { return new WP_Error( 'not_found', __( 'Run the check again: this problem is no longer in the list.', 'fixwise' ) ); } $abs = self::abs_path( $f['file'] ); if ( ! $abs ) { return new WP_Error( 'not_found', __( 'That file is no longer there.', 'fixwise' ) ); } $code = (string) file_get_contents( $abs ); // phpcs:ignore WordPress.WP.AlternativeFunctions $lines = explode( "\n", $code ); $total = count( $lines ); $from = max( 1, $f['line'] - ( 'syntax' === $f['kind'] ? 20 : 12 ) ); $to = min( $total, $f['line'] + ( 'syntax' === $f['kind'] ? 6 : 12 ) ); $window = implode( "\n", array_slice( $lines, $from - 1, $to - $from + 1 ) ); $context = $from > 1 ? implode( "\n", array_slice( $lines, max( 0, $from - 41 ), min( 40, $from - 1 ) ) ) : ''; $res = Fixwise_API::ai( 'code-fix', array( 'title' => $f['title'], 'detail' => $f['detail'], 'file' => $f['file'], 'line' => $f['line'], 'owner' => $f['owner'], 'php' => PHP_VERSION, 'wp' => get_bloginfo( 'version' ), 'window_start' => $from, 'window' => $window, 'context' => $context, ) ); if ( is_wp_error( $res ) ) { return $res; } $new = isset( $res['fixed_code'] ) ? rtrim( (string) $res['fixed_code'], "\n" ) : ''; $new = preg_replace( '/^```[a-z]*\n|\n```$/', '', $new ); // in case the model added fences $can = ! empty( $res['can_fix'] ) && '' !== trim( $new ) && $new !== $window; $fix = array( 'id' => $id, 'file' => $f['file'], 'from' => $from, 'to' => $to, 'old' => $window, 'new' => $can ? $new : '', 'md5' => md5( $code ), 'explanation' => (string) ( $res['explanation'] ?? '' ), 'severity' => (string) ( $res['severity'] ?? '' ), 'summary' => array_slice( array_map( 'strval', (array) ( $res['change_summary'] ?? array() ) ), 0, 3 ), 'manual' => (string) ( $res['manual_steps'] ?? '' ), // Fixwise never changes theme or plugin files: the owner copies the corrected lines into the file. 'can_apply' => $can, 'why_not' => $can && ! $f['fixable'] ? __( 'This file belongs to a theme or plugin from WordPress.org, so its next update would undo a change made here. Send the explanation to its developer, or put the fix in a child theme.', 'fixwise' ) : '', 'at' => time(), ); if ( $fix['can_apply'] ) { // The fixed file must at least parse on this server's PHP. $check = self::replace_lines( $code, $from, $to, $new ); try { token_get_all( $check, TOKEN_PARSE ); } catch ( Throwable $e ) { $fix['can_apply'] = false; $fix['new'] = ''; $fix['why_not'] = __( 'The suggested code did not pass PHP\'s syntax check, so Fixwise does not show it. Use the explanation instead.', 'fixwise' ); } } $all = (array) get_option( self::FIXES, array() ); $all[ $id ] = $fix; update_option( self::FIXES, array_slice( $all, -30, null, true ), false ); return array( 'fix' => $fix, 'code' => self::state() ); } /** Replaces lines $from..$to (1-based) with $new, keeping the file's line endings. */ public static function replace_lines( $code, $from, $to, $new ) { $lines = explode( "\n", $code ); $new = explode( "\n", str_replace( "\r\n", "\n", $new ) ); if ( false !== strpos( $code, "\r\n" ) ) { $new = array_map( function ( $l ) { return $l . "\r"; }, $new ); } array_splice( $lines, $from - 1, $to - $from + 1, $new ); return implode( "\n", $lines ); } /** Versions before 1.2.5 could save AI fixes into files and kept safety copies: remove those copies. */ public static function cleanup_old() { foreach ( (array) get_option( self::BACKUPS, array() ) as $b ) { if ( is_array( $b ) && ! empty( $b['copy'] ) && is_file( $b['copy'] ) && false !== strpos( wp_normalize_path( $b['copy'] ), '/fixwise-backups-' ) ) { wp_delete_file( $b['copy'] ); } } delete_option( self::BACKUPS ); } public static function discard( $id ) { $all = (array) get_option( self::FIXES, array() ); unset( $all[ $id ] ); update_option( self::FIXES, $all, false ); return array( 'code' => self::state() ); } public static function fix_for( $id ) { $all = (array) get_option( self::FIXES, array() ); return isset( $all[ $id ] ) ? array( 'fix' => $all[ $id ] ) : new WP_Error( 'not_found', __( 'No suggestion saved for this problem.', 'fixwise' ) ); } }