Search in sources :

Example 11 with Page

use of org.apache.wiki.api.core.Page in project jspwiki by apache.

the class AtomFeed method getItems.

private Collection<Element> getItems() {
    final ArrayList<Element> list = new ArrayList<>();
    final Engine engine = m_wikiContext.getEngine();
    ServletContext servletContext = null;
    if (m_wikiContext.getHttpRequest() != null) {
        servletContext = m_wikiContext.getHttpRequest().getSession().getServletContext();
    }
    for (final Entry e : m_entries) {
        final Page p = e.getPage();
        final Element entryEl = getElement("entry");
        // Mandatory elements
        entryEl.addContent(getElement("id").setText(getEntryID(e)));
        entryEl.addContent(getElement("title").setAttribute("type", "html").setText(e.getTitle()));
        entryEl.addContent(getElement("updated").setText(DateFormatUtils.formatUTC(p.getLastModified(), RFC3339FORMAT)));
        // Optional elements
        entryEl.addContent(getElement("author").addContent(getElement("name").setText(e.getAuthor())));
        entryEl.addContent(getElement("link").setAttribute("rel", "alternate").setAttribute("href", e.getURL()));
        entryEl.addContent(getElement("content").setAttribute("type", "html").setText(e.getContent()));
        // Check for enclosures
        if (engine.getManager(AttachmentManager.class).hasAttachments(p) && servletContext != null) {
            try {
                final List<Attachment> c = engine.getManager(AttachmentManager.class).listAttachments(p);
                for (final Attachment att : c) {
                    final Element attEl = getElement("link");
                    attEl.setAttribute("rel", "enclosure");
                    attEl.setAttribute("href", engine.getURL(ContextEnum.PAGE_ATTACH.getRequestContext(), att.getName(), null));
                    attEl.setAttribute("length", Long.toString(att.getSize()));
                    attEl.setAttribute("type", getMimeType(servletContext, att.getFileName()));
                    entryEl.addContent(attEl);
                }
            } catch (final ProviderException ex) {
            // FIXME: log.info("Can't get attachment data",ex);
            }
        }
        list.add(entryEl);
    }
    return list;
}
Also used : ProviderException(org.apache.wiki.api.exceptions.ProviderException) Element(org.jdom2.Element) ArrayList(java.util.ArrayList) ServletContext(javax.servlet.ServletContext) Page(org.apache.wiki.api.core.Page) Attachment(org.apache.wiki.api.core.Attachment) AttachmentManager(org.apache.wiki.attachment.AttachmentManager) Engine(org.apache.wiki.api.core.Engine)

Example 12 with Page

use of org.apache.wiki.api.core.Page in project jspwiki by apache.

the class DefaultRSSGenerator method generateBlogRSS.

/**
 * {@inheritDoc}
 */
@Override
public String generateBlogRSS(final Context wikiContext, final List<Page> changed, final Feed feed) {
    log.debug("Generating RSS for blog, size={}", changed.size());
    final String ctitle = m_engine.getManager(VariableManager.class).getVariable(wikiContext, PROP_CHANNEL_TITLE);
    if (ctitle != null) {
        feed.setChannelTitle(ctitle);
    } else {
        feed.setChannelTitle(m_engine.getApplicationName() + ":" + wikiContext.getPage().getName());
    }
    feed.setFeedURL(wikiContext.getViewURL(wikiContext.getPage().getName()));
    final String language = m_engine.getManager(VariableManager.class).getVariable(wikiContext, PROP_CHANNEL_LANGUAGE);
    if (language != null) {
        feed.setChannelLanguage(language);
    } else {
        feed.setChannelLanguage(m_channelLanguage);
    }
    final String channelDescription = m_engine.getManager(VariableManager.class).getVariable(wikiContext, PROP_CHANNEL_DESCRIPTION);
    if (channelDescription != null) {
        feed.setChannelDescription(channelDescription);
    }
    changed.sort(new PageTimeComparator());
    int items = 0;
    for (final Iterator<Page> i = changed.iterator(); i.hasNext() && items < 15; items++) {
        final Page page = i.next();
        final Entry e = new Entry();
        e.setPage(page);
        final String url;
        if (page instanceof Attachment) {
            url = m_engine.getURL(ContextEnum.PAGE_ATTACH.getRequestContext(), page.getName(), null);
        } else {
            url = m_engine.getURL(ContextEnum.PAGE_VIEW.getRequestContext(), page.getName(), null);
        }
        e.setURL(url);
        // Title
        String pageText = m_engine.getManager(PageManager.class).getPureText(page.getName(), WikiProvider.LATEST_VERSION);
        String title = "";
        final int firstLine = pageText.indexOf('\n');
        if (firstLine > 0) {
            title = pageText.substring(0, firstLine).trim();
        }
        if (title.isEmpty()) {
            title = page.getName();
        }
        // Remove wiki formatting
        while (title.startsWith("!")) {
            title = title.substring(1);
        }
        e.setTitle(title);
        // Description
        if (firstLine > 0) {
            int maxlen = pageText.length();
            if (maxlen > MAX_CHARACTERS) {
                maxlen = MAX_CHARACTERS;
            }
            pageText = m_engine.getManager(RenderingManager.class).textToHTML(wikiContext, pageText.substring(firstLine + 1, maxlen).trim());
            if (maxlen == MAX_CHARACTERS) {
                pageText += "...";
            }
            e.setContent(pageText);
        } else {
            e.setContent(title);
        }
        e.setAuthor(getAuthor(page));
        feed.addEntry(e);
    }
    return feed.getString();
}
Also used : VariableManager(org.apache.wiki.variables.VariableManager) PageManager(org.apache.wiki.pages.PageManager) Page(org.apache.wiki.api.core.Page) Attachment(org.apache.wiki.api.core.Attachment) PageTimeComparator(org.apache.wiki.pages.PageTimeComparator)

Example 13 with Page

use of org.apache.wiki.api.core.Page in project jspwiki by apache.

the class InsertPage method execute.

/**
 *  {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public String execute(final Context context, final Map<String, String> params) throws PluginException {
    final Engine engine = context.getEngine();
    final StringBuilder res = new StringBuilder();
    final String clazz = params.get(PARAM_CLASS);
    final String includedPage = params.get(PARAM_PAGENAME);
    String style = params.get(PARAM_STYLE);
    final boolean showOnce = "once".equals(params.get(PARAM_SHOW));
    final String defaultstr = params.get(PARAM_DEFAULT);
    final int section = TextUtil.parseIntParameter(params.get(PARAM_SECTION), -1);
    int maxlen = TextUtil.parseIntParameter(params.get(PARAM_MAXLENGTH), -1);
    final ResourceBundle rb = Preferences.getBundle(context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE);
    if (style == null) {
        style = DEFAULT_STYLE;
    }
    if (maxlen == -1) {
        maxlen = Integer.MAX_VALUE;
    }
    if (includedPage != null) {
        final Page page;
        try {
            final String pageName = engine.getFinalPageName(includedPage);
            if (pageName != null) {
                page = engine.getManager(PageManager.class).getPage(pageName);
            } else {
                page = engine.getManager(PageManager.class).getPage(includedPage);
            }
        } catch (final 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 = 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<>();
            }
            // Check for permissions
            final AuthorizationManager mgr = engine.getManager(AuthorizationManager.class);
            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();
            }
            // Show Once
            // Check for page-cookie, only include page if cookie is not yet set
            String cookieName = "";
            if (showOnce) {
                cookieName = ONCE_COOKIE + TextUtil.urlEncodeUTF8(page.getName()).replaceAll("\\+", "%20");
                if (HttpUtil.retrieveCookieValue(context.getHttpRequest(), cookieName) != null) {
                    // silent exit
                    return "";
                }
            }
            // move here, after premature exit points (permissions, page-cookie)
            previousIncludes.add(page.getName());
            context.setVariable(ATTR_RECURSE, previousIncludes);
            /**
             *  We want inclusion to occur within the context of
             *  its own page, because we need the links to be correct.
             */
            final Context includedContext = context.clone();
            includedContext.setPage(page);
            String pageData = engine.getManager(PageManager.class).getPureText(page);
            String moreLink = "";
            if (section != -1) {
                try {
                    pageData = TextUtil.getSection(pageData, section);
                } catch (final IllegalArgumentException e) {
                    throw new PluginException(e.getMessage());
                }
            }
            if (pageData.length() > maxlen) {
                pageData = pageData.substring(0, maxlen) + " ...";
                moreLink = "<p><a href=\"" + context.getURL(ContextEnum.PAGE_VIEW.getRequestContext(), includedPage) + "\">" + rb.getString("insertpage.more") + "</a></p>";
            }
            res.append("<div class=\"inserted-page ");
            if (clazz != null)
                res.append(clazz);
            if (!style.equals(DEFAULT_STYLE))
                res.append("\" style=\"").append(style);
            if (showOnce)
                res.append("\" data-once=\"").append(cookieName);
            res.append("\" >");
            res.append(engine.getManager(RenderingManager.class).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 '").append(includedPage).append("'.  Would you like to ");
                res.append("<a href=\"").append(context.getURL(ContextEnum.PAGE_EDIT.getRequestContext(), includedPage)).append("\">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 : Context(org.apache.wiki.api.core.Context) ProviderException(org.apache.wiki.api.exceptions.ProviderException) PluginException(org.apache.wiki.api.exceptions.PluginException) Page(org.apache.wiki.api.core.Page) PageManager(org.apache.wiki.pages.PageManager) ResourceBundle(java.util.ResourceBundle) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) Engine(org.apache.wiki.api.core.Engine)

Example 14 with Page

use of org.apache.wiki.api.core.Page in project jspwiki by apache.

the class DefaultPageManager method saveText.

@Override
public void saveText(final Context context, final String text) throws WikiException {
    // Check if page data actually changed; bail if not
    final Page page = context.getPage();
    final String oldText = getPureText(page);
    final String proposedText = TextUtil.normalizePostData(text);
    if (oldText != null && oldText.equals(proposedText)) {
        return;
    }
    // Check if creation of empty pages is allowed; bail if not
    final boolean allowEmpty = TextUtil.getBooleanProperty(m_engine.getWikiProperties(), Engine.PROP_ALLOW_CREATION_OF_EMPTY_PAGES, false);
    if (!allowEmpty && !wikiPageExists(page) && text.trim().equals("")) {
        return;
    }
    // Create approval workflow for page save; add the diffed, proposed and old text versions as
    // Facts for the approver (if approval is required). If submitter is authenticated, any reject
    // messages will appear in his/her workflow inbox.
    final WorkflowBuilder builder = WorkflowBuilder.getBuilder(m_engine);
    final Principal submitter = context.getCurrentUser();
    final Step prepTask = m_engine.getManager(TasksManager.class).buildPreSaveWikiPageTask(proposedText);
    final Step completionTask = m_engine.getManager(TasksManager.class).buildSaveWikiPageTask();
    final String diffText = m_engine.getManager(DifferenceManager.class).makeDiff(context, oldText, proposedText);
    final boolean isAuthenticated = context.getWikiSession().isAuthenticated();
    final Fact[] facts = new Fact[5];
    facts[0] = new Fact(WorkflowManager.WF_WP_SAVE_FACT_PAGE_NAME, page.getName());
    facts[1] = new Fact(WorkflowManager.WF_WP_SAVE_FACT_DIFF_TEXT, diffText);
    facts[2] = new Fact(WorkflowManager.WF_WP_SAVE_FACT_PROPOSED_TEXT, proposedText);
    facts[3] = new Fact(WorkflowManager.WF_WP_SAVE_FACT_CURRENT_TEXT, oldText);
    facts[4] = new Fact(WorkflowManager.WF_WP_SAVE_FACT_IS_AUTHENTICATED, isAuthenticated);
    final String rejectKey = isAuthenticated ? WorkflowManager.WF_WP_SAVE_REJECT_MESSAGE_KEY : null;
    final Workflow workflow = builder.buildApprovalWorkflow(submitter, WorkflowManager.WF_WP_SAVE_APPROVER, prepTask, WorkflowManager.WF_WP_SAVE_DECISION_MESSAGE_KEY, facts, completionTask, rejectKey);
    workflow.start(context);
    // Let callers know if the page-save requires approval
    if (workflow.getCurrentStep() instanceof Decision) {
        throw new DecisionRequiredException("The page contents must be approved before they become active.");
    }
}
Also used : DecisionRequiredException(org.apache.wiki.workflow.DecisionRequiredException) Workflow(org.apache.wiki.workflow.Workflow) Page(org.apache.wiki.api.core.Page) Step(org.apache.wiki.workflow.Step) TasksManager(org.apache.wiki.tasks.TasksManager) Fact(org.apache.wiki.workflow.Fact) Decision(org.apache.wiki.workflow.Decision) DifferenceManager(org.apache.wiki.diff.DifferenceManager) WorkflowBuilder(org.apache.wiki.workflow.WorkflowBuilder) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) Principal(java.security.Principal)

Example 15 with Page

use of org.apache.wiki.api.core.Page in project jspwiki by apache.

the class DefaultPageManager method actionPerformed.

/**
 * Listens for {@link org.apache.wiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED}
 * events. If a user profile's name changes, each page ACL is inspected. If an entry contains
 * a name that has changed, it is replaced with the new one. No events are emitted
 * as a consequence of this method, because the page contents are still the same; it is
 * only the representations of the names within the ACL that are changing.
 *
 * @param event The event
 */
@Override
public void actionPerformed(final WikiEvent event) {
    if (!(event instanceof WikiSecurityEvent)) {
        return;
    }
    final WikiSecurityEvent se = (WikiSecurityEvent) event;
    if (se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED) {
        final UserProfile[] profiles = (UserProfile[]) se.getTarget();
        final Principal[] oldPrincipals = new Principal[] { new WikiPrincipal(profiles[0].getLoginName()), new WikiPrincipal(profiles[0].getFullname()), new WikiPrincipal(profiles[0].getWikiName()) };
        final Principal newPrincipal = new WikiPrincipal(profiles[1].getFullname());
        // Examine each page ACL
        try {
            int pagesChanged = 0;
            final Collection<Page> pages = getAllPages();
            for (final Page page : pages) {
                final boolean aclChanged = changeAcl(page, oldPrincipals, newPrincipal);
                if (aclChanged) {
                    // If the Acl needed changing, change it now
                    try {
                        m_engine.getManager(AclManager.class).setPermissions(page, page.getAcl());
                    } catch (final WikiSecurityException e) {
                        LOG.error("Could not change page ACL for page " + page.getName() + ": " + e.getMessage(), e);
                    }
                    pagesChanged++;
                }
            }
            LOG.info("Profile name change for '" + newPrincipal + "' caused " + pagesChanged + " page ACLs to change also.");
        } catch (final ProviderException e) {
            // Oooo! This is really bad...
            LOG.error("Could not change user name in Page ACLs because of Provider error:" + e.getMessage(), e);
        }
    }
}
Also used : UserProfile(org.apache.wiki.auth.user.UserProfile) ProviderException(org.apache.wiki.api.exceptions.ProviderException) Page(org.apache.wiki.api.core.Page) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) WikiSecurityEvent(org.apache.wiki.event.WikiSecurityEvent) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) Principal(java.security.Principal) AclManager(org.apache.wiki.auth.acl.AclManager)

Aggregations

Page (org.apache.wiki.api.core.Page)181 PageManager (org.apache.wiki.pages.PageManager)106 Test (org.junit.jupiter.api.Test)71 Context (org.apache.wiki.api.core.Context)46 Engine (org.apache.wiki.api.core.Engine)30 Attachment (org.apache.wiki.api.core.Attachment)27 ProviderException (org.apache.wiki.api.exceptions.ProviderException)22 Date (java.util.Date)21 WikiPage (org.apache.wiki.WikiPage)18 ReferenceManager (org.apache.wiki.references.ReferenceManager)16 RenderingManager (org.apache.wiki.render.RenderingManager)15 AttachmentManager (org.apache.wiki.attachment.AttachmentManager)14 File (java.io.File)11 ArrayList (java.util.ArrayList)10 Calendar (java.util.Calendar)10 Hashtable (java.util.Hashtable)10 IOException (java.io.IOException)9 Vector (java.util.Vector)9 TestEngine (org.apache.wiki.TestEngine)9 PagePermission (org.apache.wiki.auth.permissions.PagePermission)8