$vars Public query variables. * @return array */ public function query_vars( array $vars ): array { $vars[] = 'vabelon_lang'; return $vars; } /** * Add a copy of each rule that starts with a language prefix. * * @param array $rules Rules of one family. * @return array */ public function prefix_rules( array $rules ): array { $group = $this->language_group(); if ( '' === $group ) { return $rules; } $root = 'root_rewrite_rules' === current_filter(); $prefixed = array(); foreach ( $rules as $regex => $query ) { $regex = ltrim( $regex, '^' ); if ( $root && 1 !== preg_match( '#^(?:page/|feed/|\((?:\?:)?feed\|)#', $regex ) ) { continue; } $shifted = preg_replace_callback( '/\$matches\[([0-9]+)\]/', static function ( array $found ): string { return '$matches[' . ( (int) $found[1] + 1 ) . ']'; }, $query ); $target = is_string( $shifted ) ? $shifted : $query; $prefixed[ $group . $regex ] = $target . ( false === strpos( $target, '?' ) ? '?' : '&' ) . 'vabelon_lang=$matches[1]'; } return $prefixed + $rules; } /** * Add the rule for each language's home address. * * @return void */ public function add_home_rule(): void { $group = $this->language_group(); if ( '' !== $group ) { add_rewrite_rule( $group . '?$', 'index.php?vabelon_lang=$matches[1]', 'top' ); } } /** * Rebuild WordPress's rules when the languages or the address structure changed. * * @return void */ public function maybe_flush(): void { $signature = hash( 'sha256', (string) wp_json_encode( array( VABELON_VERSION, Plugin::languages()->all(), get_option( 'permalink_structure', '' ) ) ) ); if ( get_option( 'vabelon_rewrite_signature', '' ) === $signature ) { return; } flush_rewrite_rules( false ); update_option( 'vabelon_rewrite_signature', $signature, false ); } /** * Stop WordPress redirecting a language address to another language. * * @param mixed $redirect Address WordPress wants to redirect to. * @param mixed $requested Address that was requested. * @return mixed */ public function keep_language( $redirect, $requested ) { if ( ! is_string( $redirect ) || ! is_string( $requested ) ) { return $redirect; } $asked = Plugin::urls()->language_from_url( $requested ); if ( Plugin::languages()->default_slug() !== $asked && Plugin::urls()->language_from_url( $redirect ) !== $asked ) { return false; } return $redirect; } /** * Regex group matching every language prefix except the default, followed by a slash. * * @return string */ private function language_group(): string { $slugs = Plugin::languages()->non_default_slugs(); if ( array() === $slugs ) { return ''; } return '(' . implode( '|', array_map( static fn( string $slug ): string => preg_quote( $slug, '#' ), $slugs ) ) . ')/'; } }