001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019package org.apache.wiki.plugin; 020 021import org.apache.wiki.api.core.Context; 022import org.apache.wiki.api.exceptions.PluginException; 023import org.apache.wiki.api.plugin.Plugin; 024import org.apache.wiki.render.RenderingManager; 025 026import jakarta.servlet.http.HttpServletRequest; 027import java.util.ArrayList; 028import java.util.Comparator; 029import java.util.HashMap; 030import java.util.List; 031import java.util.Locale; 032import java.util.Map; 033import java.util.ResourceBundle; 034 035/** 036 * Shows the content that matches the language preference of the visitor, as the browser sends it in the {@code Accept-Language} 037 * header. The body holds one block per language, written as {@code :xx:text::} with the language code between colons, and an optional 038 * {@code :else:text::} block for visitors that none of the blocks suits: 039 * 040 * <pre> 041 * [{LanguagePlugin 042 * 043 * :de:Willkommen:: :en:Welcome:: :else:Welcome / Willkommen::}] 044 * </pre> 045 * 046 * <p>The languages of the visitor are tried in the order of their quality values, and a block matches when its code is the language of 047 * the tag, so {@code de} matches {@code de-AT}. Only the language is compared, not the region. If no block matches and there is no 048 * {@code :else:} block, nothing is shown. The text of the chosen block is rendered as wiki markup. A block ends at the first 049 * {@code ::}, so the text of a block cannot contain it.</p> 050 * 051 * <p>Parameters: none.</p> 052 * 053 * @since 3.0.1 054 */ 055public class LanguagePlugin implements Plugin { 056 057 /** The code of the block that is shown when none of the languages of the visitor has a block. */ 058 private static final String ELSE = "else"; 059 060 /** A language tag of the {@code Accept-Language} header with its quality value. */ 061 private static final class Preference { 062 final String language; 063 final double quality; 064 065 Preference( final String language, final double quality ) { 066 this.language = language; 067 this.quality = quality; 068 } 069 } 070 071 /** {@inheritDoc} */ 072 @Override 073 public String getDisplayName( final Locale locale ) { 074 final ResourceBundle rb = ResourceBundle.getBundle( PluginManager.PLUGIN_I18N_RESOURCE, locale ); 075 return rb.getString( this.getClass().getSimpleName() ); 076 } 077 078 /** {@inheritDoc} */ 079 @Override 080 public String getSnipExample() { 081 return "LanguagePlugin\n\n:de:{text}:: :en:{text}:: :else:{text}::\n"; 082 } 083 084 /** {@inheritDoc} */ 085 @Override 086 public String execute( final Context context, final Map< String, String > params ) throws PluginException { 087 final String body = params.get( DefaultPluginManager.PARAM_BODY ); 088 if( body == null || body.isEmpty() ) { 089 return ""; 090 } 091 final HttpServletRequest request = context.getHttpRequest(); 092 final String header = request == null ? null : request.getHeader( "Accept-Language" ); 093 final Map< String, String > blocks = parseBlocks( body ); 094 String text = null; 095 for( final String language : parse( header ) ) { 096 text = blocks.get( language.toLowerCase( Locale.ROOT ) ); 097 if( text != null ) { 098 break; 099 } 100 } 101 if( text == null ) { 102 text = blocks.get( ELSE ); 103 if( text == null ) { 104 return ""; 105 } 106 } 107 return context.getEngine().getManager( RenderingManager.class ).textToHTML( context, text.trim() ); 108 } 109 110 /** 111 * Splits the body into its blocks, written as {@code :xx:text::}. The body is scanned once, without regular expressions, because 112 * it is written by the authors of the page and a pattern with a lazy match would take a time that grows with the square of its 113 * length on a crafted body. When a code occurs more than once, the first block is kept. 114 * 115 * @param body the body of the plugin. 116 * @return the text of each block by its code in lower case, with the else block under {@code else}. 117 */ 118 static Map< String, String > parseBlocks( final String body ) { 119 final Map< String, String > blocks = new HashMap<>(); 120 int position = 0; 121 while( position < body.length() ) { 122 final int start = body.indexOf( ':', position ); 123 if( start < 0 ) { 124 break; 125 } 126 final int codeEnd = body.indexOf( ':', start + 1 ); 127 if( codeEnd < 0 ) { 128 break; 129 } 130 final String code = body.substring( start + 1, codeEnd ); 131 if( isCode( code ) ) { 132 final int end = body.indexOf( "::", codeEnd + 1 ); 133 if( end < 0 ) { 134 break; 135 } 136 blocks.putIfAbsent( code.toLowerCase( Locale.ROOT ), body.substring( codeEnd + 1, end ) ); 137 position = end + 2; 138 } else { 139 position = start + 1; 140 } 141 } 142 return blocks; 143 } 144 145 /** A code is a language of two or three letters, or the word else. */ 146 private static boolean isCode( final String code ) { 147 if( ELSE.equals( code ) ) { 148 return true; 149 } 150 if( code.length() < 2 || code.length() > 3 ) { 151 return false; 152 } 153 for( int i = 0; i < code.length(); i++ ) { 154 final char c = code.charAt( i ); 155 if( !( c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' ) ) { 156 return false; 157 } 158 } 159 return true; 160 } 161 162 /** 163 * Reads the languages of an {@code Accept-Language} header, most preferred first. Tags with a quality of zero and the wildcard are 164 * left out, and so are entries that cannot be read. 165 * 166 * @param header the value of the header, may be {@code null}. 167 * @return the languages, without region, in the order of preference. 168 */ 169 static List< String > parse( final String header ) { 170 final List< Preference > preferences = new ArrayList<>(); 171 if( header == null ) { 172 return new ArrayList<>(); 173 } 174 for( final String entry : header.split( "," ) ) { 175 final String[] parts = entry.trim().split( ";" ); 176 final String tag = parts[ 0 ].trim(); 177 if( tag.isEmpty() || tag.equals( "*" ) ) { 178 continue; 179 } 180 double quality = 1.0; 181 for( int i = 1; i < parts.length; i++ ) { 182 final String parameter = parts[ i ].trim(); 183 if( parameter.regionMatches( true, 0, "q=", 0, 2 ) ) { 184 try { 185 quality = Double.parseDouble( parameter.substring( 2 ).trim() ); 186 } catch( final NumberFormatException e ) { 187 quality = 0; 188 } 189 } 190 } 191 if( quality > 0 ) { 192 final int dash = tag.indexOf( '-' ); 193 preferences.add( new Preference( dash < 0 ? tag : tag.substring( 0, dash ), quality ) ); 194 } 195 } 196 preferences.sort( Comparator.comparingDouble( ( final Preference p ) -> p.quality ).reversed() ); 197 final List< String > languages = new ArrayList<>(); 198 for( final Preference preference : preferences ) { 199 languages.add( preference.language ); 200 } 201 return languages; 202 } 203 204}