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.search;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.commons.lang3.time.StopWatch;
023import org.apache.logging.log4j.LogManager;
024import org.apache.logging.log4j.Logger;
025import org.apache.wiki.ajax.AjaxUtil;
026import org.apache.wiki.ajax.WikiAjaxDispatcherServlet;
027import org.apache.wiki.ajax.WikiAjaxServlet;
028import org.apache.wiki.api.core.Context;
029import org.apache.wiki.api.core.ContextEnum;
030import org.apache.wiki.api.core.Engine;
031import org.apache.wiki.api.core.Page;
032import org.apache.wiki.api.exceptions.FilterException;
033import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
034import org.apache.wiki.api.filters.BasePageFilter;
035import org.apache.wiki.api.search.SearchResult;
036import org.apache.wiki.api.spi.Wiki;
037import org.apache.wiki.auth.AuthorizationManager;
038import org.apache.wiki.auth.permissions.PermissionFactory;
039import org.apache.wiki.event.WikiEvent;
040import org.apache.wiki.event.WikiEventManager;
041import org.apache.wiki.event.WikiPageEvent;
042import org.apache.wiki.pages.PageManager;
043import org.apache.wiki.parser.MarkupParser;
044import org.apache.wiki.references.ReferenceManager;
045import org.apache.wiki.util.ClassUtil;
046import org.apache.wiki.util.TextUtil;
047
048import javax.servlet.http.HttpServletRequest;
049import javax.servlet.http.HttpServletResponse;
050import java.io.IOException;
051import java.util.ArrayList;
052import java.util.Collection;
053import java.util.HashMap;
054import java.util.Iterator;
055import java.util.List;
056import java.util.Map;
057import java.util.Properties;
058import java.util.Set;
059
060
061/**
062 *  Manages searching the Wiki.
063 *
064 *  @since 2.2.21.
065 */
066public class DefaultSearchManager extends BasePageFilter implements SearchManager {
067
068    private static final Logger LOG = LogManager.getLogger( DefaultSearchManager.class );
069
070    private SearchProvider m_searchProvider;
071
072    /**
073     *  Creates a new SearchManager.
074     *
075     *  @param engine The Engine that owns this SearchManager.
076     *  @param properties The list of Properties.
077     *  @throws FilterException If it cannot be instantiated.
078     */
079    public DefaultSearchManager( final Engine engine, final Properties properties ) throws FilterException {
080        initialize( engine, properties );
081        WikiEventManager.addWikiEventListener( m_engine.getManager( PageManager.class ), this );
082
083        // TODO: Replace with custom annotations. See JSPWIKI-566
084        WikiAjaxDispatcherServlet.registerServlet( JSON_SEARCH, new JSONSearch() );
085    }
086
087    /**
088     *  Provides a JSON AJAX API to the JSPWiki Search Engine.
089     */
090    public class JSONSearch implements WikiAjaxServlet {
091
092        public static final String AJAX_ACTION_SUGGESTIONS = "suggestions";
093        public static final String AJAX_ACTION_PAGES = "pages";
094        public static final int DEFAULT_MAX_RESULTS = 20;
095        public int maxResults = DEFAULT_MAX_RESULTS;
096
097        /** {@inheritDoc} */
098        @Override
099        public String getServletMapping() {
100            return JSON_SEARCH;
101        }
102
103        /** {@inheritDoc} */
104        @Override
105        public void service( final HttpServletRequest req,
106                             final HttpServletResponse resp,
107                             final String actionName,
108                             final List< String > params ) throws IOException {
109            String result = "";
110            if( StringUtils.isNotBlank( actionName ) ) {
111                if( params.isEmpty() ) {
112                    return;
113                }
114                final String itemId = params.get( 0 );
115                LOG.debug( "itemId=" + itemId );
116                if( params.size() > 1 ) {
117                    final String maxResultsParam = params.get( 1 );
118                    LOG.debug( "maxResultsParam=" + maxResultsParam );
119                    if( StringUtils.isNotBlank( maxResultsParam ) && StringUtils.isNumeric( maxResultsParam ) ) {
120                        maxResults = Integer.parseInt( maxResultsParam );
121                    }
122                }
123
124                if( actionName.equals( AJAX_ACTION_SUGGESTIONS ) ) {
125                    LOG.debug( "Calling getSuggestions() START" );
126                    final Context wikiContext = Wiki.context().create( m_engine, req, ContextEnum.PAGE_VIEW.getRequestContext() );
127                    final List< String > callResults = getSuggestions( itemId, maxResults, wikiContext );
128                    LOG.debug( "Calling getSuggestions() DONE. " + callResults.size() );
129                    result = AjaxUtil.toJson( callResults );
130                } else if( actionName.equals( AJAX_ACTION_PAGES ) ) {
131                    LOG.debug("Calling findPages() START");
132                    final Context wikiContext = Wiki.context().create( m_engine, req, ContextEnum.PAGE_VIEW.getRequestContext() );
133                    final List< Map< String, Object > > callResults = findPages( itemId, maxResults, wikiContext );
134                    LOG.debug( "Calling findPages() DONE. " + callResults.size() );
135                    result = AjaxUtil.toJson( callResults );
136                }
137            }
138            LOG.debug( "result=" + result );
139            resp.getWriter().write( result );
140        }
141
142        /** The suggestions are shown to everybody, so they hold only the names of the pages that the viewer may view. */
143        private boolean mayView( final Context wikiContext, final String pageName ) {
144            final Page page = m_engine.getManager( PageManager.class ).getPage( pageName );
145            return page == null || m_engine.getManager( AuthorizationManager.class )
146                                           .checkPermission( wikiContext.getWikiSession(), PermissionFactory.getPagePermission( page, "view" ) );
147        }
148
149        /**
150         *  Provides a list of suggestions to use for a page name. Currently, the algorithm just looks into the value parameter,
151         *  and returns all page names from that.
152         *
153         *  @param wikiName the page name
154         *  @param maxLength maximum number of suggestions
155         *  @param wikiContext the context of the viewer, whose view permission decides which page names are suggested
156         *  @return the suggestions
157         */
158        public List< String > getSuggestions( String wikiName, final int maxLength, final Context wikiContext ) {
159            final StopWatch sw = new StopWatch();
160            sw.start();
161            final List< String > list = new ArrayList<>( maxLength );
162            if( !wikiName.isEmpty() ) {
163                // split pagename and attachment filename
164                String filename = "";
165                final int pos = wikiName.indexOf("/");
166                if( pos >= 0 ) {
167                    filename = wikiName.substring( pos ).toLowerCase();
168                    wikiName = wikiName.substring( 0, pos );
169                }
170
171                final String cleanWikiName = MarkupParser.cleanLink(wikiName).toLowerCase() + filename;
172                final String oldStyleName = MarkupParser.wikifyLink(wikiName).toLowerCase() + filename;
173                final Set< String > allPages = m_engine.getManager( ReferenceManager.class ).findCreated();
174
175                int counter = 0;
176                for( final Iterator< String > i = allPages.iterator(); i.hasNext() && counter < maxLength; ) {
177                    final String p = i.next();
178                    final String pp = p.toLowerCase();
179                    if( ( pp.startsWith( cleanWikiName) || pp.startsWith( oldStyleName ) ) && mayView( wikiContext, p ) ) {
180                        list.add( p );
181                        counter++;
182                    }
183                }
184            }
185
186            sw.stop();
187            LOG.debug( "Suggestion request for {} done in {}", wikiName, sw );
188            return list;
189        }
190
191        /**
192         *  Performs a full search of pages.
193         *
194         *  @param searchString The query string
195         *  @param maxLength How many hits to return
196         *  @return the pages found
197         */
198        public List< Map< String, Object > > findPages( final String searchString, final int maxLength, final Context wikiContext ) {
199            final StopWatch sw = new StopWatch();
200            sw.start();
201
202            final List< Map< String, Object > > list = new ArrayList<>( maxLength );
203            if( !searchString.isEmpty() ) {
204                try {
205                    final Collection< SearchResult > c;
206                    if( m_searchProvider instanceof LuceneSearchProvider ) {
207                        c = ( ( LuceneSearchProvider )m_searchProvider ).findPages( searchString, 0, wikiContext );
208                    } else {
209                        c = m_searchProvider.findPages( searchString, wikiContext );
210                    }
211
212                    int count = 0;
213                    for( final Iterator< SearchResult > i = c.iterator(); i.hasNext() && count < maxLength; count++ ) {
214                        final SearchResult sr = i.next();
215                        final HashMap< String, Object > hm = new HashMap<>();
216                        hm.put( "page", sr.getPage().getName() );
217                        hm.put( "score", sr.getScore() );
218                        list.add( hm );
219                    }
220                } catch( final Exception e ) {
221                    LOG.info( "AJAX search failed; ", e );
222                }
223            }
224
225            sw.stop();
226            LOG.debug( "AJAX search complete in {}", sw );
227            return list;
228        }
229    }
230
231
232    /** {@inheritDoc} */
233    @Override
234    public void initialize( final Engine engine, final Properties properties ) throws FilterException {
235        m_engine = engine;
236        loadSearchProvider(properties);
237
238        try {
239            m_searchProvider.initialize( engine, properties );
240        } catch( final NoRequiredPropertyException | IOException e ) {
241            LOG.error( e.getMessage(), e );
242        }
243    }
244
245    private void loadSearchProvider( final Properties properties ) {
246        // See if we're using Lucene, and if so, ensure that its index directory is up-to-date.
247        final String providerClassName = TextUtil.getStringProperty( properties, PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER );
248
249        try {
250            m_searchProvider = ClassUtil.buildInstance( "org.apache.wiki.search", providerClassName );
251        } catch( final ReflectiveOperationException e ) {
252            LOG.warn( "Failed loading SearchProvider, will use BasicSearchProvider.", e );
253        }
254
255        if( null == m_searchProvider ) {
256            m_searchProvider = new BasicSearchProvider();
257        }
258        LOG.debug( "Loaded search provider {}", m_searchProvider );
259    }
260
261    /** {@inheritDoc} */
262    @Override
263    public SearchProvider getSearchEngine()
264    {
265        return m_searchProvider;
266    }
267
268    /** {@inheritDoc} */
269    @Override
270    public void actionPerformed( final WikiEvent event ) {
271        if( event instanceof WikiPageEvent ) {
272            final String pageName = ( ( WikiPageEvent ) event ).getPageName();
273            if( event.getType() == WikiPageEvent.PAGE_DELETE_REQUEST ) {
274                final Page p = m_engine.getManager( PageManager.class ).getPage( pageName );
275                if( p != null ) {
276                    pageRemoved( p );
277                }
278            }
279            if( event.getType() == WikiPageEvent.PAGE_REINDEX ) {
280                final Page p = m_engine.getManager( PageManager.class ).getPage( pageName );
281                if( p != null ) {
282                    reindexPage( p );
283                }
284            }
285        }
286    }
287
288}