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.content;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Attachment;
024import org.apache.wiki.api.core.Context;
025import org.apache.wiki.api.core.Engine;
026import org.apache.wiki.api.core.Page;
027import org.apache.wiki.api.exceptions.ProviderException;
028import org.apache.wiki.api.exceptions.WikiException;
029import org.apache.wiki.attachment.AttachmentManager;
030import org.apache.wiki.event.WikiEventManager;
031import org.apache.wiki.event.WikiPageRenameEvent;
032import org.apache.wiki.pages.PageManager;
033import org.apache.wiki.parser.MarkupParser;
034import org.apache.wiki.references.ReferenceManager;
035import org.apache.wiki.search.SearchManager;
036import org.apache.wiki.util.TextUtil;
037
038import java.util.Collection;
039import java.util.List;
040import java.util.Set;
041import java.util.TreeSet;
042import java.util.regex.Matcher;
043import java.util.regex.Pattern;
044import org.apache.wiki.event.WikiPageRenameEvent;
045import org.apache.wiki.security.EventUtil;
046
047
048/**
049 * Provides page renaming functionality. Note that there used to be a similarly named class in 2.6, but due to unclear copyright, the
050 * class was completely rewritten from scratch for 2.8.
051 *
052 * @since 2.8
053 */
054public class DefaultPageRenamer implements PageRenamer {
055
056    private static final Logger LOG = LogManager.getLogger( DefaultPageRenamer.class );
057    
058    /** Plugin invocations and variable assignments whose parameter names a page: {@code [{InsertPage page='X'}]}, {@code [{SET alias='X'}]}. */
059    private static final Pattern PAGE_PARAMETER_INVOCATION = Pattern.compile( "(?<!\\[)(?<!~)(\\[\\{\\s*)(InsertPage|SET)(\\s[^}]*)\\}\\]" );
060    private static final Pattern PAGE_PARAMETER = Pattern.compile( "(\\b(?:page|alias)\\s*=\\s*)(?:'([^']*)'|\"([^\"]*)\"|([^\\s'\"]+))" );
061
062    private boolean m_camelCase;
063    
064    /**
065     *  Renames a page.
066     *  
067     *  @param context The current context.
068     *  @param renameFrom The name from which to rename.
069     *  @param renameTo The new name.
070     *  @param changeReferrers If true, also changes all the referrers.
071     *  @return The final new name (in case it had to be modified)
072     *  @throws WikiException If the page cannot be renamed.
073     */
074    @Override
075    public String renamePage( final Context context, final String renameFrom, final String renameTo, final boolean changeReferrers ) throws WikiException {
076        //  Sanity checks first
077        if( renameFrom == null || renameFrom.isEmpty() ) {
078            throw new WikiException( "From name may not be null or empty" );
079        }
080        if( renameTo == null || renameTo.isEmpty() ) {
081            throw new WikiException( "To name may not be null or empty" );
082        }
083       
084        //  Clean up the "to" -name so that it does not contain anything illegal
085        final String renameToClean = MarkupParser.cleanLink( renameTo.trim() );
086        if( renameToClean.equals( renameFrom ) ) {
087            throw new WikiException( "You cannot rename the page to itself" );
088        }
089        
090        //  Preconditions: "from" page must exist, and "to" page must not yet exist.
091        final Engine engine = context.getEngine();
092        final Page fromPage = engine.getManager( PageManager.class ).getPage( renameFrom );
093        if( fromPage == null ) {
094            throw new WikiException("No such page "+renameFrom);
095        }
096        Page toPage = engine.getManager( PageManager.class ).getPage( renameToClean );
097        if( toPage != null ) {
098            throw new WikiException( "Page already exists " + renameToClean );
099        }
100        
101        final Set< String > referrers = getReferencesToChange( fromPage, renameToClean, engine );
102
103        //  Do the actual rename by changing from the frompage to the topage, including all the attachments
104        //  Remove references to attachments under old name
105        final List< Attachment > attachmentsOldName = engine.getManager( AttachmentManager.class ).listAttachments( fromPage );
106        for( final Attachment att: attachmentsOldName ) {
107            final Page fromAttPage = engine.getManager( PageManager.class ).getPage( att.getName() );
108            engine.getManager( ReferenceManager.class ).pageRemoved( fromAttPage );
109        }
110
111        engine.getManager( PageManager.class ).getProvider().movePage( renameFrom, renameToClean );
112        if( engine.getManager( AttachmentManager.class ).attachmentsEnabled() ) {
113            engine.getManager( AttachmentManager.class ).getCurrentProvider().moveAttachmentsForPage( renameFrom, renameToClean );
114        }
115        
116        //  Add a comment to the page notifying what changed.  This adds a new revision to the repo with no actual change.
117        toPage = engine.getManager( PageManager.class ).getPage( renameToClean );
118        if( toPage == null ) {
119            throw new ProviderException( "Rename seems to have failed for some strange reason - please check logs!" );
120        }
121        toPage.setAttribute( Page.CHANGENOTE, fromPage.getName() + " ==> " + toPage.getName() );
122        toPage.setAuthor( context.getCurrentUser().getName() );
123        engine.getManager( PageManager.class ).putPageText( toPage, engine.getManager( PageManager.class ).getPureText( toPage ) );
124
125        //  Update the references
126        engine.getManager( ReferenceManager.class ).pageRemoved( fromPage );
127        engine.getManager( ReferenceManager.class ).updateReferences( toPage );
128
129        //  Update referrers
130        if( changeReferrers ) {
131            updateReferrers( context, fromPage, toPage, referrers );
132        }
133
134        //  re-index the page including its attachments
135        engine.getManager( SearchManager.class ).reindexPage( toPage );
136        
137        final Collection< Attachment > attachmentsNewName = engine.getManager( AttachmentManager.class ).listAttachments( toPage );
138        for( final Attachment att:attachmentsNewName ) {
139            final Page toAttPage = engine.getManager( PageManager.class ).getPage( att.getName() );
140            // add reference to attachment under new page name
141            engine.getManager( ReferenceManager.class ).updateReferences( toAttPage );
142            engine.getManager( SearchManager.class ).reindexPage( att );
143        }
144
145        firePageRenameEvent( renameFrom, renameToClean, context );
146
147        //  Done, return the new name.
148        return renameToClean;
149    }
150
151    /**
152     * Fires a WikiPageRenameEvent to all registered listeners. Currently not used internally by JSPWiki itself, but you can use it for
153     * something else.
154     *
155     * @param oldName the former page name
156     * @param newName the new page name
157     */
158    @Override
159    public void firePageRenameEvent( final String oldName, final String newName, final Context context) {
160        if( WikiEventManager.isListening(this) ) {
161            WikiEventManager.fireEvent(this, EventUtil.applyFrom(new WikiPageRenameEvent(this, oldName, newName ), context) );
162        }
163    }
164
165    /**
166     *  This method finds all the pages which have anything to do with the fromPage and
167     *  change any referrers it can figure out in that page.
168     *  
169     *  @param context WikiContext in which we operate
170     *  @param fromPage The old page
171     *  @param toPage The new page
172     */
173    private void updateReferrers( final Context context, final Page fromPage, final Page toPage, final Set< String > referrers ) {
174        if( referrers.isEmpty() ) { // No referrers
175            return;
176        }
177
178        final Engine engine = context.getEngine();
179        for( String pageName : referrers ) {
180            //  In case the page was just changed from under us, let's do this small kludge.
181            if( pageName.equals( fromPage.getName() ) ) {
182                pageName = toPage.getName();
183            }
184            
185            final Page p = engine.getManager( PageManager.class ).getPage( pageName );
186
187            final String sourceText = engine.getManager( PageManager.class ).getPureText( p );
188            String newText = replaceReferrerString(sourceText, fromPage.getName(), toPage.getName() );
189            newText = replacePageParameters( newText, fromPage.getName(), toPage.getName() );
190
191            m_camelCase = TextUtil.getBooleanProperty( engine.getWikiProperties(), MarkupParser.PROP_CAMELCASELINKS, m_camelCase );
192            if( m_camelCase ) {
193                newText = replaceCCReferrerString(newText, fromPage.getName(), toPage.getName() );
194            }
195            
196            if( !sourceText.equals( newText ) ) {
197                p.setAttribute( Page.CHANGENOTE, fromPage.getName()+" ==> "+toPage.getName() );
198                p.setAuthor( context.getCurrentUser().getName() );
199         
200                try {
201                    engine.getManager( PageManager.class ).putPageText( p, newText );
202                    engine.getManager( ReferenceManager.class ).updateReferences( p );
203                } catch( final ProviderException e ) {
204                    //  We fail with an error, but we will try to continue to rename other referrers as well.
205                    LOG.error("Unable to perform rename.",e);
206                }
207            }
208        }
209    }
210
211    private Set<String> getReferencesToChange( final Page fromPage, final String renameTo, final Engine engine ) {
212        final Set< String > referrers = new TreeSet<>();
213        final Collection< String > r = engine.getManager( ReferenceManager.class ).findReferrers( fromPage.getName() );
214        if( r != null ) {
215            referrers.addAll( r );
216        }
217        
218        try {
219            final List< Attachment > attachments = engine.getManager( AttachmentManager.class ).listAttachments( fromPage );
220            for( final Attachment att : attachments  ) {
221                final Collection< String > c = engine.getManager( ReferenceManager.class ).findReferrers( att.getName() );
222                if( c != null ) {
223                    referrers.addAll( c );
224                }
225            }
226        } catch( final ProviderException e ) {
227            // We will continue despite this error
228            LOG.error( "Provider error while fetching attachments for rename", e );
229        }
230        referrers.addAll( findPageParameterReferrers( fromPage, renameTo, engine ) );
231        return referrers;
232    }
233
234    /**
235     * Finds the pages that name {@code fromPage} in a plugin or variable parameter. The {@link ReferenceManager} doesn't know about them,
236     * as they aren't links, so every page has to be looked at.
237     */
238    private Set< String > findPageParameterReferrers( final Page fromPage, final String renameTo, final Engine engine ) {
239        final Set< String > referrers = new TreeSet<>();
240        try {
241            for( final Page page : engine.getManager( PageManager.class ).getAllPages() ) {
242                final String text = engine.getManager( PageManager.class ).getPureText( page );
243                if( !replacePageParameters( text, fromPage.getName(), renameTo ).equals( text ) ) {
244                    referrers.add( page.getName() );
245                }
246            }
247        } catch( final ProviderException e ) {
248            // We will continue despite this error
249            LOG.error( "Provider error while looking for page parameters for rename", e );
250        }
251        return referrers;
252    }
253
254    /**
255     *  Replaces the page named by the {@code page} parameter of InsertPage and by the {@code alias} parameter of SET.
256     */
257    private String replacePageParameters( final String sourceText, final String from, final String to ) {
258        final Matcher invocation = PAGE_PARAMETER_INVOCATION.matcher( sourceText );
259        final StringBuilder sb = new StringBuilder( sourceText.length() + 32 );
260        int start = 0;
261        while( invocation.find() ) {
262            final String parameterName = "InsertPage".equals( invocation.group( 2 ) ) ? "page" : "alias";
263            final Matcher parameter = PAGE_PARAMETER.matcher( invocation.group( 3 ) );
264            final StringBuilder parameters = new StringBuilder();
265            int parametersStart = 0;
266            while( parameter.find() ) {
267                parameters.append( invocation.group( 3 ), parametersStart, parameter.start() );
268                parametersStart = parameter.end();
269                final String quote = parameter.group( 2 ) != null ? "'" : parameter.group( 3 ) != null ? "\"" : "";
270                final String value = parameter.group( 2 ) != null ? parameter.group( 2 ) : parameter.group( 3 ) != null ? parameter.group( 3 ) : parameter.group( 4 );
271                final boolean namesPage = parameter.group( 1 ).startsWith( parameterName ) && isSamePage( value, from );
272                parameters.append( parameter.group( 1 ) );
273                if( namesPage ) {
274                    final String newQuote = quote.isEmpty() && to.indexOf( ' ' ) != -1 ? "'" : quote;
275                    parameters.append( newQuote ).append( to ).append( newQuote );
276                } else {
277                    parameters.append( quote ).append( value ).append( quote );
278                }
279            }
280            parameters.append( invocation.group( 3 ).substring( parametersStart ) );
281            sb.append( sourceText, start, invocation.start() )
282              .append( invocation.group( 1 ) ).append( invocation.group( 2 ) ).append( parameters ).append( "}]" );
283            start = invocation.end();
284        }
285        return sb.append( sourceText.substring( start ) ).toString();
286    }
287
288    private boolean isSamePage( final String value, final String from ) {
289        return value.equals( from ) || MarkupParser.cleanLink( value ).equals( from );
290    }
291
292    /**
293     *  Replaces camelcase links.
294     */
295    private String replaceCCReferrerString( final String sourceText, final String from, final String to ) {
296        final StringBuilder sb = new StringBuilder( sourceText.length()+32 );
297        final Pattern linkPattern = Pattern.compile( "\\p{Lu}+\\p{Ll}+\\p{Lu}+[\\p{L}\\p{Digit}]*" );
298        final Matcher matcher = linkPattern.matcher( sourceText );
299        int start = 0;
300        
301        while( matcher.find( start ) ) {
302            final String match = matcher.group();
303            sb.append( sourceText, start, matcher.start() );
304            final int lastOpenBrace = sourceText.lastIndexOf( '[', matcher.start() );
305            final int lastCloseBrace = sourceText.lastIndexOf( ']', matcher.start() );
306            
307            if( match.equals( from ) && lastCloseBrace >= lastOpenBrace ) {
308                sb.append( to );
309            } else {
310                sb.append( match );
311            }
312            
313            start = matcher.end();
314        }
315        
316        sb.append( sourceText.substring( start ) );
317        
318        return sb.toString();
319    }
320
321    private String replaceReferrerString(final String sourceText, final String from, final String to ) {
322        final StringBuilder sb = new StringBuilder( sourceText.length()+32 );
323        
324        // This monstrosity just looks for a JSPWiki link pattern.  But it is pretty cool for a regexp, isn't it?  If you can
325        // understand this in a single reading, you have way too much time in your hands.
326        final Pattern linkPattern = Pattern.compile( "([\\[~]?)\\[([^|\\]]*)(\\|)?([^|\\]]*)(\\|)?([^|\\]]*)]" );
327        final Matcher matcher = linkPattern.matcher( sourceText );
328        int start = 0;
329        
330        while( matcher.find( start ) ) {
331            char charBefore = (char)-1;
332            
333            if( matcher.start() > 0 ) {
334                charBefore = sourceText.charAt( matcher.start() - 1 );
335            }
336            
337            if( !matcher.group(1).isEmpty() || charBefore == '~' || charBefore == '[' ) {
338                //  Found an escape character, so I am escaping.
339                sb.append( sourceText, start, matcher.end() );
340                start = matcher.end();
341                continue;
342            }
343
344            String text = matcher.group(2);
345            String link = matcher.group(4);
346            final String attr = matcher.group(6);
347             
348            if( link.isEmpty() ) {
349                text = replaceSingleLink(text, from, to, true );
350            } else {
351                link = replaceSingleLink(link, from, to, false );
352                
353                //  A very simple substitution, but should work for quite a few cases.
354                text = TextUtil.replaceString( text, from, to );
355            }
356        
357            //
358            //  Construct the new string
359            //
360            sb.append( sourceText, start, matcher.start() );
361            sb.append( "[" ).append( text );
362            if( !link.isEmpty() ) {
363                sb.append( "|" ).append( link );
364            }
365            if( !attr.isEmpty() ) {
366                sb.append( "|" ).append( attr );
367            }
368            sb.append( "]" );
369            
370            start = matcher.end();
371        }
372        
373        sb.append( sourceText.substring( start ) );
374        
375        return sb.toString();
376    }
377
378    /**
379     *  This method does a correct replacement of a single link, taking into account anchors and attachments. When {@code introduceLink}
380     *  is {@code true}, the original is also the visible text, so a name with blanks is kept as the text of a new link.
381     */
382    private String replaceSingleLink(final String original, final String from, final String newlink, final boolean introduceLink ) {
383        final int hash = original.indexOf( '#' );
384        final int slash = original.indexOf( '/' );
385        String realLink = original;
386
387        if( hash != -1 ) {
388            realLink = original.substring( 0, hash );
389        }
390        if( slash != -1 ) {
391            realLink = original.substring( 0,slash );
392        }
393
394        realLink = MarkupParser.cleanLink( realLink );
395        final String oldStyleRealLink = MarkupParser.wikifyLink( realLink );
396        
397        //WikiPage realPage  = context.getEngine().getPage( reallink );
398        // WikiPage p2 = context.getEngine().getPage( from );
399        
400        // System.out.println("   "+reallink+" :: "+ from);
401        // System.out.println("   "+p+" :: "+p2);
402        
403        //
404        //  Yes, these point to the same page.
405        //
406        if( realLink.equals( from ) || original.equals( from ) || oldStyleRealLink.equals( from ) ) {
407            //
408            //  if the original contains blanks, then we should introduce a link, for example:  [My Page]  =>  [My Page|My Renamed Page]
409            final int blank = realLink.indexOf( " ");
410            
411            if( introduceLink && blank != -1 ) {
412                return original + "|" + newlink;
413            }
414            
415            return newlink + ( ( hash > 0 ) ? original.substring( hash ) : "" ) + ( ( slash > 0 ) ? original.substring( slash ) : "" ) ;
416        }
417        
418        return original;
419    }
420
421}