Search in sources :

Example 1 with FilterManager

use of org.apache.wiki.filters.FilterManager in project jspwiki by apache.

the class ApprovalWorkflowTest method testSaveWikiPageWithException.

@Test
public void testSaveWikiPageWithException() {
    // Add a PageFilter that rejects all save attempts
    final FilterManager fm = m_engine.getManager(FilterManager.class);
    fm.addPageFilter(new AbortFilter(), 0);
    // Create a sample test page and try to save it
    final String pageName = "SaveWikiPageWorkflow-Test" + System.currentTimeMillis();
    final String text = "This is a test!";
    final FilterException fe = Assertions.assertThrows(FilterException.class, () -> m_engine.saveTextAsJanne(pageName, text));
    Assertions.assertEquals("Page save aborted.", fe.getMessage());
}
Also used : FilterException(org.apache.wiki.api.exceptions.FilterException) FilterManager(org.apache.wiki.filters.FilterManager) Test(org.junit.jupiter.api.Test)

Example 2 with FilterManager

use of org.apache.wiki.filters.FilterManager in project jspwiki by apache.

the class DefaultUserManager method validateProfile.

/**
 * {@inheritDoc}
 */
@Override
public void validateProfile(final Context context, final UserProfile profile) {
    final Session session = context.getWikiSession();
    final InputValidator validator = new InputValidator(SESSION_MESSAGES, context);
    final ResourceBundle rb = Preferences.getBundle(context, InternationalizationManager.CORE_BUNDLE);
    // Query the SpamFilter first
    final FilterManager fm = m_engine.getManager(FilterManager.class);
    final List<PageFilter> ls = fm.getFilterList();
    for (final PageFilter pf : ls) {
        if (pf instanceof SpamFilter) {
            if (!((SpamFilter) pf).isValidUserProfile(context, profile)) {
                session.addMessage(SESSION_MESSAGES, "Invalid userprofile");
                return;
            }
            break;
        }
    }
    // If container-managed auth and user not logged in, throw an error
    if (m_engine.getManager(AuthenticationManager.class).isContainerAuthenticated() && !context.getWikiSession().isAuthenticated()) {
        session.addMessage(SESSION_MESSAGES, rb.getString("security.error.createprofilebeforelogin"));
    }
    validator.validateNotNull(profile.getLoginName(), rb.getString("security.user.loginname"));
    validator.validateNotNull(profile.getFullname(), rb.getString("security.user.fullname"));
    validator.validate(profile.getEmail(), rb.getString("security.user.email"), InputValidator.EMAIL);
    if (!m_engine.getManager(AuthenticationManager.class).isContainerAuthenticated()) {
        final String password = profile.getPassword();
        if (password == null) {
            if (profile.isNew()) {
                // If new profile, passwords must match and can't be null
                session.addMessage(SESSION_MESSAGES, rb.getString("security.error.blankpassword"));
            }
        } else {
            final HttpServletRequest request = context.getHttpRequest();
            final String password0 = (request == null) ? null : request.getParameter("password0");
            final String password2 = (request == null) ? null : request.getParameter("password2");
            if (!password.equals(password2)) {
                session.addMessage(SESSION_MESSAGES, rb.getString("security.error.passwordnomatch"));
            }
            if (!profile.isNew() && !getUserDatabase().validatePassword(profile.getLoginName(), password0)) {
                session.addMessage(SESSION_MESSAGES, rb.getString("security.error.passwordnomatch"));
            }
        }
    }
    UserProfile otherProfile;
    final String fullName = profile.getFullname();
    final String loginName = profile.getLoginName();
    final String email = profile.getEmail();
    // It's illegal to use as a full name someone else's login name
    try {
        otherProfile = getUserDatabase().find(fullName);
        if (otherProfile != null && !profile.equals(otherProfile) && !fullName.equals(otherProfile.getFullname())) {
            final Object[] args = { fullName };
            session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.illegalfullname"), args));
        }
    } catch (final NoSuchPrincipalException e) {
    /* It's clean */
    }
    // It's illegal to use as a login name someone else's full name
    try {
        otherProfile = getUserDatabase().find(loginName);
        if (otherProfile != null && !profile.equals(otherProfile) && !loginName.equals(otherProfile.getLoginName())) {
            final Object[] args = { loginName };
            session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.illegalloginname"), args));
        }
    } catch (final NoSuchPrincipalException e) {
    /* It's clean */
    }
    // It's illegal to use multiple accounts with the same email
    try {
        otherProfile = getUserDatabase().findByEmail(email);
        if (// Issue JSPWIKI-1042
        otherProfile != null && !profile.getUid().equals(otherProfile.getUid()) && !profile.equals(otherProfile) && StringUtils.lowerCase(email).equals(StringUtils.lowerCase(otherProfile.getEmail()))) {
            final Object[] args = { email };
            session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.email.taken"), args));
        }
    } catch (final NoSuchPrincipalException e) {
    /* It's clean */
    }
}
Also used : UserProfile(org.apache.wiki.auth.user.UserProfile) SpamFilter(org.apache.wiki.filters.SpamFilter) FilterManager(org.apache.wiki.filters.FilterManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) InputValidator(org.apache.wiki.ui.InputValidator) ResourceBundle(java.util.ResourceBundle) PageFilter(org.apache.wiki.api.filters.PageFilter) Session(org.apache.wiki.api.core.Session)

Example 3 with FilterManager

use of org.apache.wiki.filters.FilterManager in project jspwiki by apache.

the class WikiEngine method initialize.

/**
 *  Does all the real initialization.
 */
private void initialize(final Properties props) throws WikiException {
    m_startTime = new Date();
    m_properties = props;
    LOG.info("*******************************************");
    LOG.info("{} {} starting. Whee!", Release.APPNAME, Release.getVersionString());
    // 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() < 3 || (m_servletContext.getMajorVersion() == 3 && m_servletContext.getMinorVersion() < 1)) {
            throw new InternalWikiException("JSPWiki requires a container which supports at least version 3.1 of Servlet specification");
        }
    }
    LOG.debug("Configuring WikiEngine...");
    // 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 {
        final 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 (final 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 = StandardCharsets.UTF_8.name().equals(TextUtil.getStringProperty(props, PROP_ENCODING, StandardCharsets.ISO_8859_1.name()));
    m_templateDir = TextUtil.getStringProperty(props, PROP_TEMPLATEDIR, "default");
    enforceValidTemplateDirectory();
    m_frontPage = TextUtil.getStringProperty(props, PROP_FRONTPAGE, "Main");
    // 
    try {
        final String aclClassName = m_properties.getProperty(PROP_ACL_MANAGER_IMPL, ClassUtil.getMappedClass(AclManager.class.getName()).getName());
        final String urlConstructorClassName = TextUtil.getStringProperty(props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor");
        final Class<URLConstructor> urlclass = ClassUtil.findClass("org.apache.wiki.url", urlConstructorClassName);
        initComponent(CommandResolver.class, this, props);
        initComponent(urlclass.getName(), URLConstructor.class);
        initComponent(CachingManager.class, this, props);
        initComponent(PageManager.class, this, props);
        initComponent(PluginManager.class, this, props);
        initComponent(DifferenceManager.class, this, props);
        initComponent(AttachmentManager.class, this, props);
        initComponent(VariableManager.class, props);
        initComponent(SearchManager.class, this, props);
        initComponent(AuthenticationManager.class);
        initComponent(AuthorizationManager.class);
        initComponent(UserManager.class);
        initComponent(GroupManager.class);
        initComponent(EditorManager.class, this);
        initComponent(ProgressManager.class, this);
        initComponent(aclClassName, AclManager.class);
        initComponent(WorkflowManager.class);
        initComponent(TasksManager.class);
        initComponent(InternationalizationManager.class, this);
        initComponent(TemplateManager.class, this, props);
        initComponent(FilterManager.class, this, props);
        initComponent(AdminBeanManager.class, this);
        initComponent(PageRenamer.class, this, props);
        // RenderingManager depends on FilterManager events.
        initComponent(RenderingManager.class);
        // ReferenceManager has the side effect of loading all pages. Therefore, after this point, all page attributes are available.
        // initReferenceManager is indirectly using m_filterManager, so it has to be called after it was initialized.
        initReferenceManager();
        // Hook the different manager routines into the system.
        getManager(FilterManager.class).addPageFilter(getManager(ReferenceManager.class), -1001);
        getManager(FilterManager.class).addPageFilter(getManager(SearchManager.class), -1002);
    } catch (final 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 (final ClassNotFoundException e) {
        LOG.fatal("JSPWiki could not start, URLConstructor was not found: {}", e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (final InstantiationException e) {
        LOG.fatal("JSPWiki could not start, URLConstructor could not be instantiated: {}", e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (final IllegalAccessException e) {
        LOG.fatal("JSPWiki could not start, URLConstructor cannot be accessed: {}", e.getMessage(), e);
        throw new WikiException(e.getMessage(), e);
    } catch (final 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);
    }
    // Initialize the good-to-have-but-not-fatal modules.
    try {
        if (TextUtil.getBooleanProperty(props, RSSGenerator.PROP_GENERATE_RSS, false)) {
            initComponent(RSSGenerator.class, this, props);
        }
    } catch (final Exception e) {
        LOG.error("Unable to start RSS generator - JSPWiki will still work, but there will be no RSS feed.", e);
    }
    final Map<String, String> extraComponents = ClassUtil.getExtraClassMappings();
    initExtraComponents(extraComponents);
    // initialization complete
    fireEvent(WikiEngineEvent.INITIALIZED);
    LOG.info("WikiEngine configured.");
    m_isConfigured = true;
}
Also used : WikiException(org.apache.wiki.api.exceptions.WikiException) SearchManager(org.apache.wiki.search.SearchManager) Date(java.util.Date) WikiException(org.apache.wiki.api.exceptions.WikiException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) ProviderException(org.apache.wiki.api.exceptions.ProviderException) FilterManager(org.apache.wiki.filters.FilterManager) ReferenceManager(org.apache.wiki.references.ReferenceManager) File(java.io.File) AclManager(org.apache.wiki.auth.acl.AclManager) URLConstructor(org.apache.wiki.url.URLConstructor)

Example 4 with FilterManager

use of org.apache.wiki.filters.FilterManager in project jspwiki by apache.

the class TableOfContents method execute.

/**
 *  {@inheritDoc}
 */
@Override
public String execute(final Context context, final Map<String, String> params) throws PluginException {
    final Engine engine = context.getEngine();
    final Page page = context.getPage();
    final ResourceBundle rb = Preferences.getBundle(context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE);
    if (context.getVariable(VAR_ALREADY_PROCESSING) != null) {
        // return rb.getString("tableofcontents.title");
        return "<a href=\"#section-TOC\" class=\"toc\">" + rb.getString("tableofcontents.title") + "</a>";
    }
    final StringBuilder sb = new StringBuilder();
    sb.append("<div class=\"toc\">\n");
    sb.append("<div class=\"collapsebox\">\n");
    final String title = params.get(PARAM_TITLE);
    sb.append("<h4 id=\"section-TOC\">");
    if (title != null) {
        sb.append(TextUtil.replaceEntities(title));
    } else {
        sb.append(rb.getString("tableofcontents.title"));
    }
    sb.append("</h4>\n");
    // should we use an ordered list?
    m_usingNumberedList = false;
    if (params.containsKey(PARAM_NUMBERED)) {
        final String numbered = params.get(PARAM_NUMBERED);
        if (numbered.equalsIgnoreCase("true")) {
            m_usingNumberedList = true;
        } else if (numbered.equalsIgnoreCase("yes")) {
            m_usingNumberedList = true;
        }
    }
    // if we are using a numbered list, get the rest of the parameters (if any) ...
    if (m_usingNumberedList) {
        int start = 0;
        final String startStr = params.get(PARAM_START);
        if ((startStr != null) && (startStr.matches("^\\d+$"))) {
            start = Integer.parseInt(startStr);
        }
        if (start < 0)
            start = 0;
        m_starting = start;
        m_level1Index = start - 1;
        if (m_level1Index < 0)
            m_level1Index = 0;
        m_level2Index = 0;
        m_level3Index = 0;
        m_prefix = TextUtil.replaceEntities(params.get(PARAM_PREFIX));
        if (m_prefix == null)
            m_prefix = "";
        m_lastLevel = Heading.HEADING_LARGE;
    }
    try {
        String wikiText = engine.getManager(PageManager.class).getPureText(page);
        final boolean runFilters = "true".equals(engine.getManager(VariableManager.class).getValue(context, VariableManager.VAR_RUNFILTERS, "true"));
        if (runFilters) {
            try {
                final FilterManager fm = engine.getManager(FilterManager.class);
                wikiText = fm.doPreTranslateFiltering(context, wikiText);
            } catch (final Exception e) {
                log.error("Could not construct table of contents: Filter Error", e);
                throw new PluginException("Unable to construct table of contents (see logs)");
            }
        }
        context.setVariable(VAR_ALREADY_PROCESSING, "x");
        final MarkupParser parser = engine.getManager(RenderingManager.class).getParser(context, wikiText);
        parser.addHeadingListener(this);
        parser.parse();
        sb.append("<ul>\n").append(m_buf).append("</ul>\n");
    } catch (final IOException e) {
        log.error("Could not construct table of contents", e);
        throw new PluginException("Unable to construct table of contents (see logs)");
    }
    sb.append("</div>\n</div>\n");
    return sb.toString();
}
Also used : PluginException(org.apache.wiki.api.exceptions.PluginException) Page(org.apache.wiki.api.core.Page) IOException(java.io.IOException) InternalWikiException(org.apache.wiki.InternalWikiException) IOException(java.io.IOException) PluginException(org.apache.wiki.api.exceptions.PluginException) FilterManager(org.apache.wiki.filters.FilterManager) PageManager(org.apache.wiki.pages.PageManager) RenderingManager(org.apache.wiki.render.RenderingManager) ResourceBundle(java.util.ResourceBundle) Engine(org.apache.wiki.api.core.Engine) MarkupParser(org.apache.wiki.parser.MarkupParser)

Aggregations

FilterManager (org.apache.wiki.filters.FilterManager)4 ResourceBundle (java.util.ResourceBundle)2 File (java.io.File)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 Date (java.util.Date)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 InternalWikiException (org.apache.wiki.InternalWikiException)1 Engine (org.apache.wiki.api.core.Engine)1 Page (org.apache.wiki.api.core.Page)1 Session (org.apache.wiki.api.core.Session)1 FilterException (org.apache.wiki.api.exceptions.FilterException)1 PluginException (org.apache.wiki.api.exceptions.PluginException)1 ProviderException (org.apache.wiki.api.exceptions.ProviderException)1 WikiException (org.apache.wiki.api.exceptions.WikiException)1 PageFilter (org.apache.wiki.api.filters.PageFilter)1 AclManager (org.apache.wiki.auth.acl.AclManager)1 UserProfile (org.apache.wiki.auth.user.UserProfile)1 SpamFilter (org.apache.wiki.filters.SpamFilter)1