Search in sources :

Example 6 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class InsertPage method execute.

/**
 *  {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public String execute(WikiContext context, Map<String, String> params) throws PluginException {
    WikiEngine engine = context.getEngine();
    StringBuilder res = new StringBuilder();
    String clazz = params.get(PARAM_CLASS);
    String includedPage = params.get(PARAM_PAGENAME);
    String style = params.get(PARAM_STYLE);
    String defaultstr = params.get(PARAM_DEFAULT);
    int section = TextUtil.parseIntParameter(params.get(PARAM_SECTION), -1);
    int maxlen = TextUtil.parseIntParameter(params.get(PARAM_MAXLENGTH), -1);
    if (style == null)
        style = DEFAULT_STYLE;
    if (maxlen == -1)
        maxlen = Integer.MAX_VALUE;
    if (includedPage != null) {
        WikiPage page = null;
        try {
            String pageName = engine.getFinalPageName(includedPage);
            if (pageName != null) {
                page = engine.getPage(pageName);
            } else {
                page = engine.getPage(includedPage);
            }
        } catch (ProviderException e) {
            res.append("<span class=\"error\">Page could not be found by the page provider.</span>");
            return res.toString();
        }
        if (page != null) {
            // 
            // Check for recursivity
            // 
            List<String> previousIncludes = (List<String>) context.getVariable(ATTR_RECURSE);
            if (previousIncludes != null) {
                if (previousIncludes.contains(page.getName())) {
                    return "<span class=\"error\">Error: Circular reference - you can't include a page in itself!</span>";
                }
            } else {
                previousIncludes = new ArrayList<String>();
            }
            previousIncludes.add(page.getName());
            context.setVariable(ATTR_RECURSE, previousIncludes);
            // 
            // Check for permissions
            // 
            AuthorizationManager mgr = engine.getAuthorizationManager();
            if (!mgr.checkPermission(context.getWikiSession(), PermissionFactory.getPagePermission(page, "view"))) {
                res.append("<span class=\"error\">You do not have permission to view this included page.</span>");
                return res.toString();
            }
            /**
             *  We want inclusion to occur within the context of
             *  its own page, because we need the links to be correct.
             */
            WikiContext includedContext = (WikiContext) context.clone();
            includedContext.setPage(page);
            String pageData = engine.getPureText(page);
            String moreLink = "";
            if (section != -1) {
                try {
                    pageData = TextUtil.getSection(pageData, section);
                } catch (IllegalArgumentException e) {
                    throw new PluginException(e.getMessage());
                }
            }
            if (pageData.length() > maxlen) {
                pageData = pageData.substring(0, maxlen) + " ...";
                moreLink = "<p><a href=\"" + context.getURL(WikiContext.VIEW, includedPage) + "\">More...</a></p>";
            }
            res.append("<div style=\"" + style + "\"" + (clazz != null ? " class=\"" + clazz + "\"" : "") + ">");
            res.append(engine.textToHTML(includedContext, pageData));
            res.append(moreLink);
            res.append("</div>");
            // 
            // Remove the name from the stack; we're now done with this.
            // 
            previousIncludes.remove(page.getName());
            context.setVariable(ATTR_RECURSE, previousIncludes);
        } else {
            if (defaultstr != null) {
                res.append(defaultstr);
            } else {
                res.append("There is no page called '" + includedPage + "'.  Would you like to ");
                res.append("<a href=\"" + context.getURL(WikiContext.EDIT, includedPage) + "\">create it?</a>");
            }
        }
    } else {
        res.append("<span class=\"error\">");
        res.append("You have to define a page!");
        res.append("</span>");
    }
    return res.toString();
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) PluginException(org.apache.wiki.api.exceptions.PluginException) List(java.util.List) ArrayList(java.util.ArrayList) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) WikiEngine(org.apache.wiki.WikiEngine)

Example 7 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class LuceneSearchProvider method findPages.

/**
 *  Searches pages using a particular combination of flags.
 *
 *  @param query The query to perform in Lucene query language
 *  @param flags A set of flags
 *  @return A Collection of SearchResult instances
 *  @throws ProviderException if there is a problem with the backend
 */
public Collection findPages(String query, int flags, WikiContext wikiContext) throws ProviderException {
    IndexSearcher searcher = null;
    ArrayList<SearchResult> list = null;
    Highlighter highlighter = null;
    try {
        String[] queryfields = { LUCENE_PAGE_CONTENTS, LUCENE_PAGE_NAME, LUCENE_AUTHOR, LUCENE_ATTACHMENTS };
        QueryParser qp = new MultiFieldQueryParser(Version.LUCENE_47, queryfields, getLuceneAnalyzer());
        // QueryParser qp = new QueryParser( LUCENE_PAGE_CONTENTS, getLuceneAnalyzer() );
        Query luceneQuery = qp.parse(query);
        if ((flags & FLAG_CONTEXTS) != 0) {
            highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"), new SimpleHTMLEncoder(), new QueryScorer(luceneQuery));
        }
        try {
            File dir = new File(m_luceneDirectory);
            Directory luceneDir = new SimpleFSDirectory(dir, null);
            IndexReader reader = DirectoryReader.open(luceneDir);
            searcher = new IndexSearcher(reader);
        } catch (Exception ex) {
            log.info("Lucene not yet ready; indexing not started", ex);
            return null;
        }
        ScoreDoc[] hits = searcher.search(luceneQuery, MAX_SEARCH_HITS).scoreDocs;
        AuthorizationManager mgr = m_engine.getAuthorizationManager();
        list = new ArrayList<SearchResult>(hits.length);
        for (int curr = 0; curr < hits.length; curr++) {
            int docID = hits[curr].doc;
            Document doc = searcher.doc(docID);
            String pageName = doc.get(LUCENE_ID);
            WikiPage page = m_engine.getPage(pageName, WikiPageProvider.LATEST_VERSION);
            if (page != null) {
                if (page instanceof Attachment) {
                // Currently attachments don't look nice on the search-results page
                // When the search-results are cleaned up this can be enabled again.
                }
                PagePermission pp = new PagePermission(page, PagePermission.VIEW_ACTION);
                if (mgr.checkPermission(wikiContext.getWikiSession(), pp)) {
                    int score = (int) (hits[curr].score * 100);
                    // Get highlighted search contexts
                    String text = doc.get(LUCENE_PAGE_CONTENTS);
                    String[] fragments = new String[0];
                    if (text != null && highlighter != null) {
                        TokenStream tokenStream = getLuceneAnalyzer().tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text));
                        fragments = highlighter.getBestFragments(tokenStream, text, MAX_FRAGMENTS);
                    }
                    SearchResult result = new SearchResultImpl(page, score, fragments);
                    list.add(result);
                }
            } else {
                log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache");
                pageRemoved(new WikiPage(m_engine, pageName));
            }
        }
    } catch (IOException e) {
        log.error("Failed during lucene search", e);
    } catch (ParseException e) {
        log.info("Broken query; cannot parse query ", e);
        throw new ProviderException("You have entered a query Lucene cannot process: " + e.getMessage());
    } catch (InvalidTokenOffsetsException e) {
        log.error("Tokens are incompatible with provided text ", e);
    } finally {
        if (searcher != null) {
            try {
                searcher.getIndexReader().close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    return list;
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) TokenStream(org.apache.lucene.analysis.TokenStream) Query(org.apache.lucene.search.Query) TermQuery(org.apache.lucene.search.TermQuery) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) StringReader(java.io.StringReader) Highlighter(org.apache.lucene.search.highlight.Highlighter) Directory(org.apache.lucene.store.Directory) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) SimpleHTMLEncoder(org.apache.lucene.search.highlight.SimpleHTMLEncoder) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryScorer(org.apache.lucene.search.highlight.QueryScorer) IOException(java.io.IOException) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) InternalWikiException(org.apache.wiki.InternalWikiException) ParseException(org.apache.lucene.queryparser.classic.ParseException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) IOException(java.io.IOException) ProviderException(org.apache.wiki.api.exceptions.ProviderException) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) IndexReader(org.apache.lucene.index.IndexReader) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) ParseException(org.apache.lucene.queryparser.classic.ParseException) SimpleHTMLFormatter(org.apache.lucene.search.highlight.SimpleHTMLFormatter) File(java.io.File) PagePermission(org.apache.wiki.auth.permissions.PagePermission)

Example 8 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class WikiEngine method initialize.

/**
 *  Does all the real initialization.
 */
private void initialize(Properties props) throws WikiException {
    m_startTime = new Date();
    m_properties = props;
    // 
    if (!c_configured) {
        String useExternalLogConfig = TextUtil.getStringProperty(props, "jspwiki.use.external.logconfig", "false");
        if (useExternalLogConfig == null || useExternalLogConfig.equals("false")) {
            PropertyConfigurator.configure(props);
        }
        c_configured = true;
    }
    log.info("*******************************************");
    log.info(Release.APPNAME + " " + Release.getVersionString() + " starting. Whee!");
    // begin initialization
    fireEvent(WikiEngineEvent.INITIALIZING);
    log.debug("Java version: " + System.getProperty("java.runtime.version"));
    log.debug("Java vendor: " + System.getProperty("java.vm.vendor"));
    log.debug("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"));
    log.debug("Default server locale: " + Locale.getDefault());
    log.debug("Default server timezone: " + TimeZone.getDefault().getDisplayName(true, TimeZone.LONG));
    if (m_servletContext != null) {
        log.info("Servlet container: " + m_servletContext.getServerInfo());
        if (m_servletContext.getMajorVersion() < 2 || (m_servletContext.getMajorVersion() == 2 && m_servletContext.getMinorVersion() < 4)) {
            throw new InternalWikiException("I require a container which supports at least version 2.4 of Servlet specification");
        }
    }
    log.debug("Configuring WikiEngine...");
    // Initializes the CommandResolver
    m_commandResolver = new CommandResolver(this, props);
    // 
    // Create and find the default working directory.
    // 
    m_workDir = TextUtil.getStringProperty(props, PROP_WORKDIR, null);
    if (m_workDir == null) {
        m_workDir = System.getProperty("java.io.tmpdir", ".");
        m_workDir += File.separator + Release.APPNAME + "-" + m_appid;
    }
    try {
        File f = new File(m_workDir);
        f.mkdirs();
        // 
        if (!f.exists())
            throw new WikiException("Work directory does not exist: " + m_workDir);
        if (!f.canRead())
            throw new WikiException("No permission to read work directory: " + m_workDir);
        if (!f.canWrite())
            throw new WikiException("No permission to write to work directory: " + m_workDir);
        if (!f.isDirectory())
            throw new WikiException("jspwiki.workDir does not point to a directory: " + m_workDir);
    } catch (SecurityException e) {
        log.fatal("Unable to find or create the working directory: " + m_workDir, e);
        throw new IllegalArgumentException("Unable to find or create the working dir: " + m_workDir, e);
    }
    log.info("JSPWiki working directory is '" + m_workDir + "'");
    m_saveUserInfo = TextUtil.getBooleanProperty(props, PROP_STOREUSERNAME, m_saveUserInfo);
    m_useUTF8 = "UTF-8".equals(TextUtil.getStringProperty(props, PROP_ENCODING, "ISO-8859-1"));
    m_beautifyTitle = TextUtil.getBooleanProperty(props, PROP_BEAUTIFYTITLE, m_beautifyTitle);
    m_templateDir = TextUtil.getStringProperty(props, PROP_TEMPLATEDIR, "default");
    m_frontPage = TextUtil.getStringProperty(props, PROP_FRONTPAGE, "Main");
    // Initialize the page name comparator now as it may be used while
    // initializing other modules
    initPageSorter(props);
    // of a better way to do the startup-sequence.
    try {
        Class<?> urlclass = ClassUtil.findClass("org.apache.wiki.url", TextUtil.getStringProperty(props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor"));
        m_urlConstructor = (URLConstructor) urlclass.newInstance();
        m_urlConstructor.initialize(this, props);
        m_pageManager = (PageManager) ClassUtil.getMappedObject(PageManager.class.getName(), this, props);
        m_pluginManager = (PluginManager) ClassUtil.getMappedObject(PluginManager.class.getName(), this, props);
        m_differenceManager = (DifferenceManager) ClassUtil.getMappedObject(DifferenceManager.class.getName(), this, props);
        m_attachmentManager = (AttachmentManager) ClassUtil.getMappedObject(AttachmentManager.class.getName(), this, props);
        m_variableManager = (VariableManager) ClassUtil.getMappedObject(VariableManager.class.getName(), props);
        // m_filterManager     = (FilterManager)ClassUtil.getMappedObject(FilterManager.class.getName(), this, props );
        m_renderingManager = (RenderingManager) ClassUtil.getMappedObject(RenderingManager.class.getName());
        m_searchManager = (SearchManager) ClassUtil.getMappedObject(SearchManager.class.getName(), this, props);
        m_authenticationManager = (AuthenticationManager) ClassUtil.getMappedObject(AuthenticationManager.class.getName());
        m_authorizationManager = (AuthorizationManager) ClassUtil.getMappedObject(AuthorizationManager.class.getName());
        m_userManager = (UserManager) ClassUtil.getMappedObject(UserManager.class.getName());
        m_groupManager = (GroupManager) ClassUtil.getMappedObject(GroupManager.class.getName());
        m_editorManager = (EditorManager) ClassUtil.getMappedObject(EditorManager.class.getName(), this);
        m_editorManager.initialize(props);
        m_progressManager = new ProgressManager();
        // Initialize the authentication, authorization, user and acl managers
        m_authenticationManager.initialize(this, props);
        m_authorizationManager.initialize(this, props);
        m_userManager.initialize(this, props);
        m_groupManager.initialize(this, props);
        m_aclManager = getAclManager();
        // Start the Workflow manager
        m_workflowMgr = (WorkflowManager) ClassUtil.getMappedObject(WorkflowManager.class.getName());
        m_workflowMgr.initialize(this, props);
        m_internationalizationManager = (InternationalizationManager) ClassUtil.getMappedObject(InternationalizationManager.class.getName(), this);
        m_templateManager = (TemplateManager) ClassUtil.getMappedObject(TemplateManager.class.getName(), this, props);
        // Since we want to use a page filters initilize() method
        // as a engine startup listener where we can initialize global event listeners,
        // it must be called lastly, so that all object references in the engine
        // are availabe to the initialize() method
        m_filterManager = (FilterManager) ClassUtil.getMappedObject(FilterManager.class.getName(), this, props);
        m_adminBeanManager = (AdminBeanManager) ClassUtil.getMappedObject(AdminBeanManager.class.getName(), this);
        // RenderingManager depends on FilterManager events.
        m_renderingManager.initialize(this, props);
        // 
        // ReferenceManager has the side effect of loading all
        // pages.  Therefore after this point, all page attributes
        // are available.
        // 
        // initReferenceManager is indirectly using m_filterManager, therefore
        // it has to be called after it was initialized.
        // 
        initReferenceManager();
        // 
        // Hook the different manager routines into the system.
        // 
        m_filterManager.addPageFilter(m_referenceManager, -1001);
        m_filterManager.addPageFilter(m_searchManager, -1002);
    } catch (RuntimeException e) {
        // RuntimeExceptions may occur here, even if they shouldn't.
        log.fatal("Failed to start managers.", e);
        throw new WikiException("Failed to start managers: " + e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        log.fatal("JSPWiki could not start, URLConstructor was not found: " + e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.fatal("JSPWiki could not start, URLConstructor could not be instantiated: " + e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        log.fatal("JSPWiki could not start, URLConstructor cannot be accessed: " + e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (Exception e) {
        // Final catch-all for everything
        log.fatal("JSPWiki could not start, due to an unknown exception when starting.", e);
        throw new WikiException("Failed to start. Caused by: " + e.getMessage() + "; please check log files for better information.", e);
    }
    // 
    try {
        if (TextUtil.getBooleanProperty(props, RSSGenerator.PROP_GENERATE_RSS, false)) {
            m_rssGenerator = (RSSGenerator) ClassUtil.getMappedObject(RSSGenerator.class.getName(), this, props);
        }
        m_pageRenamer = (PageRenamer) ClassUtil.getMappedObject(PageRenamer.class.getName(), this, props);
    } catch (Exception e) {
        log.error("Unable to start RSS generator - JSPWiki will still work, " + "but there will be no RSS feed.", e);
    }
    // Start the RSS generator & generator thread
    if (m_rssGenerator != null) {
        m_rssFile = TextUtil.getStringProperty(props, RSSGenerator.PROP_RSSFILE, "rss.rdf");
        File rssFile = null;
        if (m_rssFile.startsWith(File.separator)) {
            // honor absolute pathnames:
            rssFile = new File(m_rssFile);
        } else {
            // relative path names are anchored from the webapp root path:
            rssFile = new File(getRootPath(), m_rssFile);
        }
        int rssInterval = TextUtil.getIntegerProperty(props, RSSGenerator.PROP_INTERVAL, 3600);
        RSSThread rssThread = new RSSThread(this, rssFile, rssInterval);
        rssThread.start();
    }
    // initialization complete
    fireEvent(WikiEngineEvent.INITIALIZED);
    log.info("WikiEngine configured.");
    m_isConfigured = true;
}
Also used : WikiException(org.apache.wiki.api.exceptions.WikiException) RSSThread(org.apache.wiki.rss.RSSThread) WorkflowManager(org.apache.wiki.workflow.WorkflowManager) GroupManager(org.apache.wiki.auth.authorize.GroupManager) FilterManager(org.apache.wiki.api.engine.FilterManager) AdminBeanManager(org.apache.wiki.api.engine.AdminBeanManager) PluginManager(org.apache.wiki.api.engine.PluginManager) TemplateManager(org.apache.wiki.ui.TemplateManager) EditorManager(org.apache.wiki.ui.EditorManager) InternationalizationManager(org.apache.wiki.i18n.InternationalizationManager) SearchManager(org.apache.wiki.search.SearchManager) RSSGenerator(org.apache.wiki.rss.RSSGenerator) CommandResolver(org.apache.wiki.ui.CommandResolver) Date(java.util.Date) WikiException(org.apache.wiki.api.exceptions.WikiException) DecisionRequiredException(org.apache.wiki.workflow.DecisionRequiredException) NoSuchVariableException(org.apache.wiki.api.exceptions.NoSuchVariableException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FilterException(org.apache.wiki.api.exceptions.FilterException) IOException(java.io.IOException) ProviderException(org.apache.wiki.api.exceptions.ProviderException) AuthenticationManager(org.apache.wiki.auth.AuthenticationManager) DifferenceManager(org.apache.wiki.diff.DifferenceManager) RenderingManager(org.apache.wiki.render.RenderingManager) UserManager(org.apache.wiki.auth.UserManager) ProgressManager(org.apache.wiki.ui.progress.ProgressManager) PageRenamer(org.apache.wiki.content.PageRenamer) AttachmentManager(org.apache.wiki.attachment.AttachmentManager) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) File(java.io.File)

Aggregations

AuthorizationManager (org.apache.wiki.auth.AuthorizationManager)8 ProviderException (org.apache.wiki.api.exceptions.ProviderException)6 WikiPage (org.apache.wiki.WikiPage)5 IOException (java.io.IOException)4 PagePermission (org.apache.wiki.auth.permissions.PagePermission)3 File (java.io.File)2 Permission (java.security.Permission)2 Date (java.util.Date)2 WikiContext (org.apache.wiki.WikiContext)2 WikiEngine (org.apache.wiki.WikiEngine)2 PluginException (org.apache.wiki.api.exceptions.PluginException)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketException (java.net.SocketException)1 DateFormat (java.text.DateFormat)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1