*/ public static function state(): array { $path = self::path(); $exists = file_exists( $path ); $contents = $exists ? (string) file_get_contents( $path ) : ''; // phpcs:ignore WordPress.WP.AlternativeFunctions return array( 'supported' => self::supported(), 'server' => \AiRankSuite\Support\Server::text( 'SERVER_SOFTWARE' ), 'path' => $path, 'exists' => $exists, 'writable' => $exists ? wp_is_writable( $path ) : wp_is_writable( dirname( $path ) ), 'contents' => $contents, 'ours' => self::extract( $contents ), 'bytes' => strlen( $contents ), 'backups' => self::backups(), ); } /** * Our block, without the marker comments. */ public static function extract( string $contents ): string { $start = '# BEGIN ' . self::MARKER; $end = '# END ' . self::MARKER; $from = strpos( $contents, $start ); $to = strpos( $contents, $end ); if ( false === $from || false === $to || $to < $from ) { return ''; } $inner = substr( $contents, $from + strlen( $start ), $to - $from - strlen( $start ) ); return trim( $inner, "\r\n" ); } /** * The mistakes that actually take sites down. * * Not a full Apache parser — that is not achievable here and a half-parser * that reports false confidence is worse than an honest short list. * * @return list */ public static function problems( string $block ): array { $problems = array(); if ( strlen( $block ) > self::MAX_BYTES ) { $problems[] = __( 'Over 64 KB — far past anything a rules file should need.', 'ai-rank-suite' ); } // Unbalanced // sections are the single // most common cause of an Apache 500 from a hand-edited file. if ( preg_match_all( '/<\s*(\w+)[^>]*>/', $block, $open ) ) { $opens = array_map( 'strtolower', $open[1] ); preg_match_all( '/<\/\s*(\w+)\s*>/', $block, $close ); $closes = array_map( 'strtolower', $close[1] ?? array() ); // Report the directive the way Apache spells it — "" in an // error message about a file that says "" reads like the // checker is talking about something else. $spelling = array(); foreach ( $open[1] as $raw ) { $spelling[ strtolower( $raw ) ] = $raw; } foreach ( array_unique( $opens ) as $tag ) { $a = count( array_keys( $opens, $tag, true ) ); $b = count( array_keys( $closes, $tag, true ) ); if ( $a !== $b ) { $problems[] = sprintf( /* translators: %s: Apache directive name, e.g. IfModule. */ __( '<%s> is opened and closed a different number of times — Apache will return 500 on every page.', 'ai-rank-suite' ), $spelling[ $tag ] ?? $tag ); } } } // Writing our own marker inside the block would nest the block in // itself and make the next save unparseable. if ( false !== stripos( $block, '# BEGIN ' . self::MARKER ) || false !== stripos( $block, '# END ' . self::MARKER ) ) { $problems[] = __( 'Remove the BEGIN/END marker lines — they are added automatically.', 'ai-rank-suite' ); } // A rewrite rule with no RewriteEngine is inert at best; inside the // wrong context it errors. if ( preg_match( '/^\s*Rewrite(Rule|Cond)/mi', $block ) && ! preg_match( '/RewriteEngine\s+On/i', $block ) ) { $problems[] = __( 'RewriteRule or RewriteCond without "RewriteEngine On" — the rules will not run.', 'ai-rank-suite' ); } // A null byte in a config file is either an encoding accident or an // attack; neither should reach disk. if ( false !== strpos( $block, "\0" ) ) { $problems[] = __( 'The text contains a null byte.', 'ai-rank-suite' ); } return $problems; } /** * Write our block, preserving everything else. * * @return array|WP_Error */ public static function save( string $block ): array|WP_Error { $path = self::path(); if ( ! self::supported() ) { return new WP_Error( 'airanksuite_htaccess_unsupported', __( 'This server does not read .htaccess. Nginx and Caddy need the equivalent rules in the server config instead.', 'ai-rank-suite' ), array( 'status' => 400 ) ); } $block = str_replace( "\r\n", "\n", trim( $block ) ); $problems = self::problems( $block ); if ( ! empty( $problems ) ) { return new WP_Error( 'airanksuite_htaccess_invalid', implode( ' ', $problems ), array( 'status' => 400, 'problems' => $problems, ) ); } $existing = file_exists( $path ) ? (string) file_get_contents( $path ) : ''; // phpcs:ignore WordPress.WP.AlternativeFunctions if ( ! ( file_exists( $path ) ? wp_is_writable( $path ) : wp_is_writable( dirname( $path ) ) ) ) { return new WP_Error( 'airanksuite_htaccess_readonly', __( 'The file is not writable. Paste the block in manually, or make it writable and try again.', 'ai-rank-suite' ), array( 'status' => 409 ) ); } // Back up before touching anything — this is the whole reason recovery // does not need FTP. self::backup( $existing ); // insert_with_markers is WordPress's own routine for exactly this: it // replaces our block and leaves every other block byte for byte. if ( ! function_exists( 'insert_with_markers' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } $lines = '' === $block ? array() : explode( "\n", $block ); $result = insert_with_markers( $path, self::MARKER, $lines ); if ( ! $result ) { return new WP_Error( 'airanksuite_htaccess_write', __( 'The write failed. Nothing was changed.', 'ai-rank-suite' ), array( 'status' => 500 ) ); } return self::state(); } /** * @return list */ public static function backups(): array { $stored = get_option( self::BACKUPS, array() ); if ( ! is_array( $stored ) ) { return array(); } $out = array(); foreach ( $stored as $id => $entry ) { if ( ! is_array( $entry ) ) { continue; } $out[] = array( 'id' => (string) $id, 'time' => (int) ( $entry['time'] ?? 0 ), 'bytes' => strlen( (string) ( $entry['body'] ?? '' ) ), ); } usort( $out, static fn( array $a, array $b ): int => $b['time'] <=> $a['time'] ); return $out; } private static function backup( string $contents ): void { $stored = get_option( self::BACKUPS, array() ); $stored = is_array( $stored ) ? $stored : array(); $stored[ (string) time() . wp_rand( 100, 999 ) ] = array( 'time' => time(), 'body' => $contents, ); // Newest first, then trim: an unbounded option is a slow database leak. uasort( $stored, static fn( array $a, array $b ): int => (int) $b['time'] <=> (int) $a['time'] ); $stored = array_slice( $stored, 0, self::MAX_KEEP, true ); update_option( self::BACKUPS, $stored, false ); } /** * Put a backup back, in full — including anything that was not ours. * * @return array|WP_Error */ public static function restore( string $id ): array|WP_Error { $stored = get_option( self::BACKUPS, array() ); if ( ! is_array( $stored ) || ! isset( $stored[ $id ] ) ) { return new WP_Error( 'airanksuite_htaccess_no_backup', __( 'That backup no longer exists.', 'ai-rank-suite' ), array( 'status' => 404 ) ); } $path = self::path(); if ( file_exists( $path ) && ! wp_is_writable( $path ) ) { return new WP_Error( 'airanksuite_htaccess_readonly', __( 'The file is not writable.', 'ai-rank-suite' ), array( 'status' => 409 ) ); } // The current state becomes a backup too, so restoring is itself // undoable — otherwise recovery is a one-way door. self::backup( file_exists( $path ) ? (string) file_get_contents( $path ) : '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions $written = file_put_contents( $path, (string) $stored[ $id ]['body'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions if ( false === $written ) { return new WP_Error( 'airanksuite_htaccess_write', __( 'The restore failed. Nothing was changed.', 'ai-rank-suite' ), array( 'status' => 500 ) ); } return self::state(); } /** * Ready-made blocks people actually want, so nobody has to write Apache * from memory to get browser caching on. * * @return list */ public static function recipes(): array { return array( array( 'id' => 'cache', 'label' => __( 'Browser caching', 'ai-rank-suite' ), 'desc' => __( 'Tells browsers to keep images, CSS and fonts instead of re-downloading them. Directly improves Core Web Vitals for returning visitors.', 'ai-rank-suite' ), 'body' => "\n ExpiresActive On\n ExpiresByType image/jpeg \"access plus 1 year\"\n ExpiresByType image/png \"access plus 1 year\"\n ExpiresByType image/webp \"access plus 1 year\"\n ExpiresByType image/svg+xml \"access plus 1 year\"\n ExpiresByType text/css \"access plus 1 month\"\n ExpiresByType application/javascript \"access plus 1 month\"\n ExpiresByType font/woff2 \"access plus 1 year\"\n", ), array( 'id' => 'gzip', 'label' => __( 'Compression', 'ai-rank-suite' ), 'desc' => __( 'Compresses HTML, CSS and JavaScript in transit. Usually cuts page weight by two thirds.', 'ai-rank-suite' ), 'body' => "\n AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css\n AddOutputFilterByType DEFLATE application/javascript application/json\n AddOutputFilterByType DEFLATE image/svg+xml application/xml\n", ), array( 'id' => 'security', 'label' => __( 'Security headers', 'ai-rank-suite' ), 'desc' => __( 'Stops your pages being framed by other sites and stops browsers guessing content types.', 'ai-rank-suite' ), 'body' => "\n Header set X-Content-Type-Options \"nosniff\"\n Header set X-Frame-Options \"SAMEORIGIN\"\n Header set Referrer-Policy \"strict-origin-when-cross-origin\"\n", ), array( 'id' => 'hotlink', 'label' => __( 'Block image hotlinking', 'ai-rank-suite' ), 'desc' => __( 'Stops other sites embedding your images and spending your bandwidth. Search engine crawlers are still allowed.', 'ai-rank-suite' ), 'body' => "\n RewriteEngine On\n RewriteCond %{HTTP_REFERER} !^$\n RewriteCond %{HTTP_REFERER} !^https?://(www\\.)?%{HTTP_HOST} [NC]\n RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|duckduckbot) [NC]\n RewriteRule \\.(jpe?g|png|gif|webp)$ - [F,NC,L]\n", ), array( 'id' => 'nosniff_uploads', 'label' => __( 'Lock down uploads', 'ai-rank-suite' ), 'desc' => __( 'Stops PHP executing from the uploads folder — the standard route in after a file-upload vulnerability.', 'ai-rank-suite' ), 'body' => "\n Require all denied\n", ), ); } }