Search in sources :

Example 86 with WikiContext

use of org.apache.wiki.WikiContext 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 87 with WikiContext

use of org.apache.wiki.WikiContext in project jspwiki by apache.

the class AttachmentsIteratorTag method doStartTag.

/**
 *  {@inheritDoc}
 */
@Override
public final int doStartTag() {
    m_wikiContext = (WikiContext) pageContext.getAttribute(WikiTagBase.ATTR_CONTEXT, PageContext.REQUEST_SCOPE);
    WikiEngine engine = m_wikiContext.getEngine();
    AttachmentManager mgr = engine.getAttachmentManager();
    WikiPage page;
    page = m_wikiContext.getPage();
    if (!mgr.attachmentsEnabled()) {
        return SKIP_BODY;
    }
    try {
        if (page != null && engine.pageExists(page)) {
            Collection atts = mgr.listAttachments(page);
            if (atts == null) {
                log.debug("No attachments to display.");
                // There are no attachments included
                return SKIP_BODY;
            }
            m_iterator = atts.iterator();
            if (m_iterator.hasNext()) {
                Attachment att = (Attachment) m_iterator.next();
                WikiContext context = (WikiContext) m_wikiContext.clone();
                context.setPage(att);
                pageContext.setAttribute(WikiTagBase.ATTR_CONTEXT, context, PageContext.REQUEST_SCOPE);
                pageContext.setAttribute(getId(), att);
            } else {
                return SKIP_BODY;
            }
        } else {
            return SKIP_BODY;
        }
        return EVAL_BODY_BUFFERED;
    } catch (ProviderException e) {
        log.fatal("Provider failed while trying to iterator through history", e);
    // FIXME: THrow something.
    }
    return SKIP_BODY;
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) Collection(java.util.Collection) Attachment(org.apache.wiki.attachment.Attachment) AttachmentManager(org.apache.wiki.attachment.AttachmentManager) WikiEngine(org.apache.wiki.WikiEngine)

Example 88 with WikiContext

use of org.apache.wiki.WikiContext in project jspwiki by apache.

the class HistoryIteratorTag method doAfterBody.

public final int doAfterBody() {
    if (bodyContent != null) {
        try {
            JspWriter out = getPreviousOut();
            out.print(bodyContent.getString());
            bodyContent.clearBody();
        } catch (IOException e) {
            log.error("Unable to get inner tag text", e);
        // FIXME: throw something?
        }
    }
    if (m_iterator != null && m_iterator.hasNext()) {
        WikiContext context = (WikiContext) m_wikiContext.clone();
        context.setPage((WikiPage) m_iterator.next());
        pageContext.setAttribute(WikiTagBase.ATTR_CONTEXT, context, PageContext.REQUEST_SCOPE);
        pageContext.setAttribute(getId(), context.getPage());
        return EVAL_BODY_BUFFERED;
    }
    return SKIP_BODY;
}
Also used : WikiContext(org.apache.wiki.WikiContext) IOException(java.io.IOException) JspWriter(javax.servlet.jsp.JspWriter)

Example 89 with WikiContext

use of org.apache.wiki.WikiContext in project jspwiki by apache.

the class AttachmentServlet method upload.

/**
 *  Uploads a specific mime multipart input set, intercepts exceptions.
 *
 *  @param req The servlet request
 *  @return The page to which we should go next.
 *  @throws RedirectException If there's an error and a redirection is needed
 *  @throws IOException If upload fails
 * @throws FileUploadException
 */
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    // If something bad happened, Upload should be able to take care of most stuff
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false);
    String nextPage = errorPage;
    String progressId = req.getParameter("progressid");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);
        UploadListener pl = new UploadListener();
        m_engine.getProgressManager().startProgress(pl, progressId);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        if (!context.hasAdminPermissions()) {
            upload.setFileSizeMax(m_maxSize);
        }
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);
        String wikipage = null;
        String changeNote = null;
        // FileItem actualFile = null;
        List<FileItem> fileItems = new java.util.ArrayList<FileItem>();
        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    // 
                    // FIXME: Kludge alert.  We must end up with the parent page name,
                    // if this is an upload of a new revision
                    // 
                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");
                    if (x != -1)
                        wikipage = wikipage.substring(0, x);
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                    if (changeNote != null) {
                        changeNote = TextUtil.replaceEntities(changeNote);
                    }
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                fileItems.add(item);
            }
        }
        if (fileItems.size() == 0) {
            throw new RedirectException("Broken file upload", errorPage);
        } else {
            for (FileItem actualFile : fileItems) {
                String filename = actualFile.getName();
                long fileSize = actualFile.getSize();
                InputStream in = actualFile.getInputStream();
                try {
                    executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw new IOException(msg, e);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
    // FIXME: In case of exceptions should absolutely
    // remove the uploaded file.
    }
    return nextPage;
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) InputStream(java.io.InputStream) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException) RedirectException(org.apache.wiki.api.exceptions.RedirectException)

Example 90 with WikiContext

use of org.apache.wiki.WikiContext in project jspwiki by apache.

the class DefaultAclManager method getPermissions.

/**
 * Returns the access control list for the page.
 * If the ACL has not been parsed yet, it is done
 * on-the-fly. If the page has a parent page, then that is tried also.
 * This method was moved from Authorizer;
 * it was consolidated with some code from AuthorizationManager.
 * This method is guaranteed to return a non-<code>null</code> Acl.
 *
 * @param page the page
 * @return the Acl representing permissions for the page
 * @since 2.2.121
 */
public Acl getPermissions(WikiPage page) {
    // 
    // Does the page already have cached ACLs?
    // 
    Acl acl = page.getAcl();
    log.debug("page=" + page.getName() + "\n" + acl);
    if (acl == null) {
        // 
        if (page instanceof Attachment) {
            WikiPage parent = m_engine.getPage(((Attachment) page).getParentName());
            acl = getPermissions(parent);
        } else {
            // 
            // Or, try parsing the page
            // 
            WikiContext ctx = new WikiContext(m_engine, page);
            ctx.setVariable(RenderingManager.VAR_EXECUTE_PLUGINS, Boolean.FALSE);
            m_engine.getHTML(ctx, page);
            if (page.getAcl() == null) {
                page.setAcl(new AclImpl());
            }
            acl = page.getAcl();
        }
    }
    return acl;
}
Also used : WikiContext(org.apache.wiki.WikiContext) WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment)

Aggregations

WikiContext (org.apache.wiki.WikiContext)90 WikiPage (org.apache.wiki.WikiPage)63 Test (org.junit.Test)40 TestEngine (org.apache.wiki.TestEngine)11 StringReader (java.io.StringReader)9 WikiEngine (org.apache.wiki.WikiEngine)9 ProviderException (org.apache.wiki.api.exceptions.ProviderException)8 IOException (java.io.IOException)7 InputStream (java.io.InputStream)7 Before (org.junit.Before)7 BufferedReader (java.io.BufferedReader)6 StringWriter (java.io.StringWriter)6 Collection (java.util.Collection)6 InputStreamReader (java.io.InputStreamReader)5 Date (java.util.Date)5 LinkCollector (org.apache.wiki.LinkCollector)5 Attachment (org.apache.wiki.attachment.Attachment)5 Properties (java.util.Properties)4 MockHttpServletRequest (net.sourceforge.stripes.mock.MockHttpServletRequest)4 WikiDocument (org.apache.wiki.parser.WikiDocument)4