Search in sources :

Example 51 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class XWikiDocumentRenderingTest method testGetRenderedContentTextRights.

public void testGetRenderedContentTextRights() throws XWikiException {
    XWikiDocument otherDocument = new XWikiDocument(new DocumentReference("otherwiki", "otherspace", "otherpage"));
    otherDocument.setContentAuthorReference(new DocumentReference("otherwiki", "XWiki", "othercontentauthor"));
    XWikiDocument sdoc = new XWikiDocument(new DocumentReference("callerwiki", "callerspace", "callerpage"));
    sdoc.setContentAuthorReference(new DocumentReference("callerwiki", "XWiki", "calleruser"));
    Document apiDocument = this.document.newDocument(getContext());
    getContext().setDoc(null);
    String content = "{{velocity}}" + "$xcontext.sdoc.contentAuthorReference $xcontext.doc $xcontext.doc.contentAuthorReference" + "{{/velocity}}";
    this.document.setContentAuthorReference(new DocumentReference("authorwiki", "XWiki", "contentauthor"));
    assertEquals("<p>$xcontext.sdoc.contentAuthorReference Space.Page authorwiki:XWiki.contentauthor</p>", this.document.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), getContext()));
    assertEquals("<p>$xcontext.sdoc.contentAuthorReference Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString()));
    assertEquals("<p>$xcontext.sdoc.contentAuthorReference Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), Syntax.XHTML_1_0.toIdString()));
    assertEquals("<p>otherwiki:XWiki.othercontentauthor Space.Page authorwiki:XWiki.contentauthor</p>", this.document.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), false, otherDocument, getContext()));
    getContext().setDoc(otherDocument);
    assertEquals("<p>$xcontext.sdoc.contentAuthorReference Space.Page authorwiki:XWiki.contentauthor</p>", this.document.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), getContext()));
    assertEquals("<p>otherwiki:XWiki.othercontentauthor Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString()));
    assertEquals("<p>otherwiki:XWiki.othercontentauthor Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), Syntax.XHTML_1_0.toIdString()));
    getContext().put("sdoc", sdoc);
    getContext().setDoc(this.document);
    assertEquals("<p>callerwiki:XWiki.calleruser Space.Page authorwiki:XWiki.contentauthor</p>", this.document.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), getContext()));
    assertEquals("<p>callerwiki:XWiki.calleruser Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString()));
    assertEquals("<p>callerwiki:XWiki.calleruser Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), Syntax.XHTML_1_0.toIdString()));
    getContext().setDoc(otherDocument);
    assertEquals("<p>$xcontext.sdoc.contentAuthorReference Space.Page authorwiki:XWiki.contentauthor</p>", this.document.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), getContext()));
    assertEquals("<p>callerwiki:XWiki.calleruser Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString()));
    assertEquals("<p>callerwiki:XWiki.calleruser Space.Page authorwiki:XWiki.contentauthor</p>", apiDocument.getRenderedContent(content, Syntax.XWIKI_2_1.toIdString(), Syntax.XHTML_1_0.toIdString()));
}
Also used : Document(com.xpn.xwiki.api.Document) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 52 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class DefaultVelocityManagerTest method getVelocityContext.

// Tests
@Test
public void getVelocityContext() throws ComponentLookupException {
    VelocityContext context = this.mocker.getComponentUnderTest().getVelocityContext();
    assertNull(context.get("doc"));
    assertNull(context.get("sdoc"));
    DocumentReference docReference = new DocumentReference("wiki", "space", "doc");
    DocumentReference sdocReference = new DocumentReference("wiki", "space", "sdoc");
    this.oldcore.getXWikiContext().setDoc(new XWikiDocument(docReference));
    this.oldcore.getXWikiContext().put("sdoc", new XWikiDocument(sdocReference));
    context = this.mocker.getComponentUnderTest().getVelocityContext();
    Document doc = (Document) context.get("doc");
    assertNotNull(doc);
    Document sdoc = (Document) context.get("sdoc");
    assertNotNull(sdoc);
    // Instances are kept the same when the documents in the context don't change
    context = this.mocker.getComponentUnderTest().getVelocityContext();
    assertSame(doc, context.get("doc"));
    assertSame(sdoc, context.get("sdoc"));
    // Instances change when the documents in the context change
    docReference = new DocumentReference("wiki", "space", "doc2");
    sdocReference = new DocumentReference("wiki", "space", "sdoc2");
    this.oldcore.getXWikiContext().setDoc(new XWikiDocument(docReference));
    this.oldcore.getXWikiContext().put("sdoc", new XWikiDocument(sdocReference));
    context = this.mocker.getComponentUnderTest().getVelocityContext();
    assertNotNull(context.get("doc"));
    assertNotSame(doc, context.get("doc"));
    assertNotNull(context.get("sdoc"));
    assertNotSame(sdoc, context.get("sdoc"));
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) VelocityContext(org.apache.velocity.VelocityContext) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Example 53 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class XWiki method include.

public String include(String topic, boolean isForm, XWikiContext context) throws XWikiException {
    String database = null, incdatabase = null;
    String prefixedTopic, localTopic;
    // Save current documents in script context
    Document currentAPIdoc = null, currentAPIcdoc = null, currentAPItdoc = null;
    ScriptContextManager scritContextManager = Utils.getComponent(ScriptContextManager.class);
    ScriptContext scontext = scritContextManager.getScriptContext();
    String currentDocName = context.getWikiId() + ":" + context.getDoc().getFullName();
    if (scontext != null) {
        currentAPIdoc = (Document) scontext.getAttribute("doc");
        currentAPIcdoc = (Document) scontext.getAttribute("cdoc");
        currentAPItdoc = (Document) scontext.getAttribute("tdoc");
    }
    try {
        int i0 = topic.indexOf(':');
        if (i0 != -1) {
            incdatabase = topic.substring(0, i0);
            database = context.getWikiId();
            context.setWikiId(incdatabase);
            prefixedTopic = topic;
            localTopic = topic.substring(i0 + 1);
        } else {
            prefixedTopic = context.getWikiId() + ":" + topic;
            localTopic = topic;
        }
        XWikiDocument doc = null;
        try {
            LOGGER.debug("Including Topic " + topic);
            try {
                @SuppressWarnings("unchecked") Set<String> includedDocs = (Set<String>) context.get("included_docs");
                if (includedDocs == null) {
                    includedDocs = new HashSet<String>();
                    context.put("included_docs", includedDocs);
                }
                if (includedDocs.contains(prefixedTopic) || currentDocName.equals(prefixedTopic)) {
                    LOGGER.warn("Error on too many recursive includes for topic " + topic);
                    return "Cannot make recursive include";
                }
                includedDocs.add(prefixedTopic);
            } catch (Exception e) {
            }
            // Get document to include
            DocumentReference targetDocumentReference = getCurrentMixedDocumentReferenceResolver().resolve(localTopic);
            doc = getDocument(targetDocumentReference, context);
            if (checkAccess("view", doc, context) == false) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access to this document is denied: " + doc);
            }
        } catch (XWikiException e) {
            LOGGER.warn("Exception Including Topic " + topic, e);
            return "Topic " + topic + " does not exist";
        }
        XWikiDocument contentdoc = doc.getTranslatedDocument(context);
        String result;
        if (isForm) {
            // We do everything in the context of the including document
            if (database != null) {
                context.setWikiId(database);
            }
            // Note: the Script macro in the new rendering checks for programming rights for the document in
            // the xwiki context.
            result = getRenderedContent(contentdoc, (XWikiDocument) context.get("doc"), context);
        } else {
            // We stay in the included document context
            // Since the Script macro checks for programming rights in the current document, we need to
            // temporarily set the contentdoc as the current doc before rendering it.
            XWikiDocument originalDoc = null;
            try {
                originalDoc = context.getDoc();
                context.put("doc", doc);
                result = getRenderedContent(contentdoc, doc, context);
            } finally {
                context.put("doc", originalDoc);
            }
        }
        try {
            @SuppressWarnings("unchecked") Set<String> includedDocs = (Set<String>) context.get("included_docs");
            if (includedDocs != null) {
                includedDocs.remove(prefixedTopic);
            }
        } catch (Exception e) {
        }
        return result;
    } finally {
        if (database != null) {
            context.setWikiId(database);
        }
        if (currentAPIdoc != null) {
            if (scontext != null) {
                scontext.setAttribute("doc", currentAPIdoc, ScriptContext.ENGINE_SCOPE);
            }
        }
        if (currentAPIcdoc != null) {
            if (scontext != null) {
                scontext.setAttribute("cdoc", currentAPIcdoc, ScriptContext.ENGINE_SCOPE);
            }
        }
        if (currentAPItdoc != null) {
            if (scontext != null) {
                scontext.setAttribute("tdoc", currentAPItdoc, ScriptContext.ENGINE_SCOPE);
            }
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ScriptContext(javax.script.ScriptContext) ParseGroovyFromString(com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString) IncludeServletAsString(com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString) XWikiDeletedDocument(com.xpn.xwiki.doc.XWikiDeletedDocument) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Document(com.xpn.xwiki.api.Document) ScriptContextManager(org.xwiki.script.ScriptContextManager) WikiManagerException(org.xwiki.wiki.manager.WikiManagerException) IOException(java.io.IOException) JobException(org.xwiki.job.JobException) ParseException(org.xwiki.rendering.parser.ParseException) QueryException(org.xwiki.query.QueryException) URIException(org.apache.commons.httpclient.URIException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HibernateException(org.hibernate.HibernateException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DocumentReference(org.xwiki.model.reference.DocumentReference) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference)

Example 54 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class CreateActionRequestHandler method loadAvailableTemplateProviders.

/**
 * @param spaceReference the space to check if there are available templates for
 * @param context the context of the current request
 * @param templateClassReference the reference to the template provider class
 * @return the available template providers for the passed space, as {@link Document}s
 */
private List<Document> loadAvailableTemplateProviders(SpaceReference spaceReference, DocumentReference templateClassReference, XWikiContext context) {
    List<Document> templates = new ArrayList<>();
    try {
        QueryManager queryManager = Utils.getComponent((Type) QueryManager.class, "secure");
        Query query = queryManager.createQuery("from doc.object(XWiki.TemplateProviderClass) as template " + "where doc.fullName not like 'XWiki.TemplateProviderTemplate' " + "order by template.name", Query.XWQL);
        // TODO: Extend the above query to include a filter on the type and allowed spaces properties so we can
        // remove the java code below, thus improving performance by not loading all the documents, but only the
        // documents we need.
        List<XWikiDocument> recommendedTemplates = new ArrayList<>();
        List<String> templateProviderDocNames = query.execute();
        for (String templateProviderName : templateProviderDocNames) {
            // get the document and template provider object
            DocumentReference reference = getCurrentMixedResolver().resolve(templateProviderName);
            // Verify that the current user has the view right on the Template document
            if (!getAuthManager().hasAccess(Right.VIEW, reference)) {
                continue;
            }
            XWikiDocument templateDoc = context.getWiki().getDocument(reference, context);
            BaseObject templateObject = templateDoc.getXObject(templateClassReference);
            // Check the template provider's visibility restrictions.
            if (isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_VISIBILITY_RESTRICTIONS_PROPERTY)) {
                List<String> creationRestrictions = getTemplateProviderRestrictions(templateObject, TP_CREATION_RESTRICTIONS_PROPERTY);
                if (creationRestrictions.size() > 0 && isTemplateProviderAllowedInSpace(templateObject, spaceReference, TP_CREATION_RESTRICTIONS_PROPERTY)) {
                    // Consider providers that have creations restrictions matching the current space as
                    // "recommended" and handle them separately.
                    recommendedTemplates.add(templateDoc);
                } else {
                    // Other visible providers.
                    templates.add(new Document(templateDoc, context));
                }
            }
        }
        EntityReferenceSerializer<String> localSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, LOCAL_SERIALIZER_HINT);
        String spaceStringReference = localSerializer.serialize(spaceReference);
        // Sort the recommended providers and promote the most specific ones.
        recommendedTemplates.sort(Comparator.comparing((XWikiDocument templateProviderDocument) -> {
            BaseObject templateProviderObject = templateProviderDocument.getXObject(templateClassReference);
            // Look at any set creation restrictions.
            List<String> restrictions = getTemplateProviderRestrictions(templateProviderObject, TP_CREATION_RESTRICTIONS_PROPERTY);
            // Return the longest (max) matching restriction reference size as being the most specific.
            return restrictions.stream().filter(restriction -> matchesRestriction(spaceStringReference, restriction)).mapToInt(restriction -> {
                SpaceReferenceResolver<String> spaceResolver = Utils.getComponent(SpaceReferenceResolver.TYPE_STRING);
                SpaceReference restrictionSpaceReference = spaceResolver.resolve(restriction);
                // The specificity score.
                int specificity = restrictionSpaceReference.getReversedReferenceChain().size();
                return specificity;
            }).max().orElse(0);
        }).reversed());
        this.recommendedTemplateProviders = recommendedTemplates.stream().map(recommendedTemplate -> new Document(recommendedTemplate, context)).collect(Collectors.toList());
        // Give priority to the providers that that specify creation restrictions
        templates.addAll(0, recommendedTemplateProviders);
    } catch (Exception e) {
        LOGGER.warn("There was an error getting the available templates for space {0}", spaceReference, e);
    }
    return templates;
}
Also used : XWiki(com.xpn.xwiki.XWiki) XWikiException(com.xpn.xwiki.XWikiException) Right(org.xwiki.security.authorization.Right) Query(org.xwiki.query.Query) EntityReference(org.xwiki.model.reference.EntityReference) LoggerFactory(org.slf4j.LoggerFactory) SpaceReference(org.xwiki.model.reference.SpaceReference) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ContextualAuthorizationManager(org.xwiki.security.authorization.ContextualAuthorizationManager) DocumentReferenceResolver(org.xwiki.model.reference.DocumentReferenceResolver) Map(java.util.Map) VelocityManager(org.xwiki.velocity.VelocityManager) ScriptContextManager(org.xwiki.script.ScriptContextManager) EntityType(org.xwiki.model.EntityType) EntityReferenceSerializer(org.xwiki.model.reference.EntityReferenceSerializer) Logger(org.slf4j.Logger) BaseObject(com.xpn.xwiki.objects.BaseObject) SpaceReferenceResolver(org.xwiki.model.reference.SpaceReferenceResolver) QueryManager(org.xwiki.query.QueryManager) Collectors(java.util.stream.Collectors) VelocityContext(org.apache.velocity.VelocityContext) Document(com.xpn.xwiki.api.Document) ScriptContext(javax.script.ScriptContext) EntityReferenceResolver(org.xwiki.model.reference.EntityReferenceResolver) List(java.util.List) Type(java.lang.reflect.Type) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Comparator(java.util.Comparator) Query(org.xwiki.query.Query) SpaceReference(org.xwiki.model.reference.SpaceReference) ArrayList(java.util.ArrayList) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) QueryManager(org.xwiki.query.QueryManager) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 55 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class ObjectResourceImpl method getObject.

@Override
public Object getObject(String wikiName, String spaceName, String pageName, String className, Integer objectNumber, Boolean withPrettyNames) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, null, true, false);
        Document doc = documentInfo.getDocument();
        com.xpn.xwiki.objects.BaseObject baseObject = getBaseObject(doc, className, objectNumber);
        if (baseObject == null) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        return this.factory.toRestObject(this.uriInfo.getBaseUri(), doc, baseObject, false, withPrettyNames);
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : BaseObject(com.xpn.xwiki.objects.BaseObject) WebApplicationException(javax.ws.rs.WebApplicationException) XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

Document (com.xpn.xwiki.api.Document)97 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)60 XWikiException (com.xpn.xwiki.XWikiException)41 XWikiRestException (org.xwiki.rest.XWikiRestException)40 DocumentReference (org.xwiki.model.reference.DocumentReference)37 BaseObject (com.xpn.xwiki.objects.BaseObject)24 Test (org.junit.Test)23 WebApplicationException (javax.ws.rs.WebApplicationException)22 ArrayList (java.util.ArrayList)16 Attachment (com.xpn.xwiki.api.Attachment)14 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)14 Vector (java.util.Vector)12 Link (org.xwiki.rest.model.jaxb.Link)10 XWikiContext (com.xpn.xwiki.XWikiContext)9 AbstractComponentTest (com.celements.common.test.AbstractComponentTest)7 Date (java.util.Date)7 XWiki (com.xpn.xwiki.api.XWiki)6 RangeIterable (org.xwiki.rest.internal.RangeIterable)6 Object (org.xwiki.rest.model.jaxb.Object)6 XWiki (com.xpn.xwiki.XWiki)5