Search in sources :

Example 16 with EntityReference

use of org.xwiki.model.reference.EntityReference in project xwiki-platform by xwiki.

the class CreateActionRequestHandler method processNewDocument.

/**
 * @param toCreate the value of the "tocreate" request parameter
 */
private void processNewDocument(String toCreate) {
    // Current space and page name.
    spaceReference = document.getDocumentReference().getLastSpaceReference();
    name = document.getDocumentReference().getName();
    // Determine if the current document is in a top-level space.
    EntityReference parentSpaceReference = spaceReference.getParent();
    boolean isTopLevelSpace = parentSpaceReference.extractReference(EntityType.SPACE) == null;
    // Remember this since we might update it below.
    String originalName = name;
    // Since WebHome is a convention, determine the real name and parent of our document.
    if (WEBHOME.equals(name)) {
        // Determine its name from the space name.
        name = spaceReference.getName();
        // Determine its space reference by looking at the space's parent.
        if (!isTopLevelSpace) {
            // The parent reference is a space reference. Use it.
            spaceReference = new SpaceReference(parentSpaceReference);
        } else {
            // Top level document, i.e. the parent reference is a wiki reference. Clear the spaceReference variable
            // so that this case is properly handled later on (as if an empty value was passed as parameter in the
            // request).
            spaceReference = null;
        }
    }
    if (TOCREATE_TERMINAL.equals(toCreate) || TOCREATE_NONTERMINAL.equals(toCreate)) {
        // Look at the request to see what the user wanted to create (terminal or non-terminal).
        isSpace = !TOCREATE_TERMINAL.equals(toCreate);
    } else if (templateProvider != null) {
        // A template provider is specified. Use it and extract the type of document.
        boolean providerTerminal = getTemplateProviderTerminalValue();
        isSpace = !providerTerminal;
    } else {
        // Last option is to check the document's original name and see if it was "WebHome".
        isSpace = WEBHOME.equals(originalName);
    }
}
Also used : SpaceReference(org.xwiki.model.reference.SpaceReference) EntityReference(org.xwiki.model.reference.EntityReference)

Example 17 with EntityReference

use of org.xwiki.model.reference.EntityReference in project xwiki-platform by xwiki.

the class CreateActionRequestHandler method getNewDocumentReference.

/**
 * @return the document reference of the new document to be created, {@code null} if a no document can be created
 *         (because the conditions are not met)
 */
public DocumentReference getNewDocumentReference() {
    DocumentReference result = null;
    if (StringUtils.isEmpty(name)) {
        // Can`t do anything without a name.
        return null;
    }
    // The new values, after the processing needed for ND below, to be used when creating the document reference.
    SpaceReference newSpaceReference = spaceReference;
    String newName = name;
    // Special handling for old spaces or new Nested Documents.
    if (isSpace) {
        EntityReference parentSpaceReference = spaceReference;
        if (parentSpaceReference == null) {
            parentSpaceReference = context.getDoc().getDocumentReference().getWikiReference();
        }
        // The new space's reference.
        newSpaceReference = new SpaceReference(name, parentSpaceReference);
        // The new document's name set to the new space's homepage. In Nested Documents, this leads to the new ND's
        // reference name.
        newName = WEBHOME;
    }
    if (newSpaceReference == null) {
        // documents can be top-level.
        return null;
    }
    // that there is no template is ok.
    if (hasTemplate() || availableTemplateProviders.isEmpty()) {
        result = new DocumentReference(newName, newSpaceReference);
    }
    return result;
}
Also used : SpaceReference(org.xwiki.model.reference.SpaceReference) EntityReference(org.xwiki.model.reference.EntityReference) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 18 with EntityReference

use of org.xwiki.model.reference.EntityReference in project xwiki-platform by xwiki.

the class DeleteAction method deleteToRecycleBin.

private boolean deleteToRecycleBin(XWikiContext context) throws XWikiException {
    XWikiRequest request = context.getRequest();
    XWikiDocument doc = context.getDoc();
    EntityReference documentReference = doesAffectChildren(request, doc.getDocumentReference()) ? doc.getDocumentReference().getLastSpaceReference() : doc.getTranslatedDocument(context).getDocumentReferenceWithLocale();
    return deleteToRecycleBin(documentReference, context);
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) EntityReference(org.xwiki.model.reference.EntityReference)

Example 19 with EntityReference

use of org.xwiki.model.reference.EntityReference in project xwiki-platform by xwiki.

the class XWikiRightServiceImpl method checkRight.

public boolean checkRight(String userOrGroupName, XWikiDocument doc, String accessLevel, boolean user, boolean allow, boolean global, XWikiContext context) throws XWikiRightNotFoundException, XWikiException {
    if (!global && ("admin".equals(accessLevel))) {
        // Admin rights do not exist at document level.
        throw new XWikiRightNotFoundException();
    }
    EntityReference rightClassReference = global ? GLOBALRIGHTCLASS_REFERENCE : RIGHTCLASS_REFERENCE;
    String fieldName = user ? "users" : "groups";
    boolean found = false;
    // Here entity is either a user or a group
    DocumentReference userOrGroupDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(userOrGroupName);
    String prefixedFullName = this.entityReferenceSerializer.serialize(userOrGroupDocumentReference);
    String shortname = userOrGroupName;
    int i0 = userOrGroupName.indexOf(":");
    if (i0 != -1) {
        shortname = userOrGroupName.substring(i0 + 1);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Checking right: [{}], [{}], [{}], [{}], [{}], [{}]", userOrGroupName, doc.getFullName(), accessLevel, user, allow, global);
    }
    List<BaseObject> rightObjects = doc.getXObjects(rightClassReference);
    if (rightObjects != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Checking objects [{}]", rightObjects.size());
        }
        for (int i = 0; i < rightObjects.size(); i++) {
            LOGGER.debug("Checking object [{}]", i);
            BaseObject bobj = rightObjects.get(i);
            if (bobj == null) {
                LOGGER.debug("Bypass object [{}]", i);
                continue;
            }
            String users = bobj.getStringValue(fieldName);
            String levels = bobj.getStringValue("levels");
            boolean allowdeny = (bobj.getIntValue("allow") == 1);
            if (allowdeny == allow) {
                LOGGER.debug("Checking match: [{}] in [{}]", accessLevel, levels);
                String[] levelsarray = StringUtils.split(levels, " ,|");
                if (ArrayUtils.contains(levelsarray, accessLevel)) {
                    LOGGER.debug("Found a right for [{}]", allow);
                    found = true;
                    LOGGER.debug("Checking match: [{}] in [{}]", userOrGroupName, users);
                    String[] userarray = GroupsClass.getListFromString(users).toArray(new String[0]);
                    for (int ii = 0; ii < userarray.length; ii++) {
                        String value = userarray[ii];
                        if (value.indexOf(".") == -1) {
                            userarray[ii] = "XWiki." + value;
                        }
                    }
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Checking match: [{}] in [{}]", userOrGroupName, StringUtils.join(userarray, ","));
                    }
                    // name is requested
                    if (doc.getWikiName().equals(userOrGroupDocumentReference.getWikiReference().getName())) {
                        if (ArrayUtils.contains(userarray, shortname)) {
                            LOGGER.debug("Found matching right in [{}] for [{}]", users, shortname);
                            return true;
                        }
                        // We should also allow to skip "XWiki." from the usernames and group
                        // lists
                        String veryshortname = shortname.substring(shortname.indexOf(".") + 1);
                        if (ArrayUtils.contains(userarray, veryshortname)) {
                            LOGGER.debug("Found matching right in [{}] for [{}]", users, shortname);
                            return true;
                        }
                    }
                    if ((context.getWikiId() != null) && (ArrayUtils.contains(userarray, userOrGroupName))) {
                        LOGGER.debug("Found matching right in [{}] for [{}]", users, userOrGroupName);
                        return true;
                    }
                    LOGGER.debug("Failed match: [{}] in [{}]", userOrGroupName, users);
                }
            } else {
                LOGGER.debug("Bypass object [{}] because wrong allow/deny", i);
            }
        }
    }
    LOGGER.debug("Searching for matching rights at group level");
    // Didn't found right at this level.. Let's go to group level
    Map<String, Collection<String>> grouplistcache = (Map<String, Collection<String>>) context.get("grouplist");
    if (grouplistcache == null) {
        grouplistcache = new HashMap<String, Collection<String>>();
        context.put("grouplist", grouplistcache);
    }
    Collection<String> grouplist = new HashSet<String>();
    // Get member groups from document's wiki
    addMemberGroups(doc.getWikiName(), prefixedFullName, userOrGroupDocumentReference, grouplist, context);
    // Get member groups from member's wiki
    if (!context.getWikiId().equalsIgnoreCase(userOrGroupDocumentReference.getWikiReference().getName())) {
        addMemberGroups(userOrGroupDocumentReference.getWikiReference().getName(), prefixedFullName, userOrGroupDocumentReference, grouplist, context);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Searching for matching rights for [{}] groups: [{}]", grouplist.size(), grouplist);
    }
    for (String group : grouplist) {
        try {
            // We need to construct the full group name to make sure the groups are
            // handled separately
            boolean result = checkRight(group, doc, accessLevel, false, allow, global, context);
            if (result) {
                return true;
            }
        } catch (XWikiRightNotFoundException e) {
        } catch (Exception e) {
            LOGGER.error("Failed to check right [{}] for group [{}] on document [ΒΆ}]", accessLevel, group, doc.getPrefixedFullName(), e);
        }
    }
    LOGGER.debug("Finished searching for rights for [{}]: [{}]", userOrGroupName, found);
    if (found) {
        return false;
    } else {
        throw new XWikiRightNotFoundException();
    }
}
Also used : XWikiException(com.xpn.xwiki.XWikiException) XWikiRightNotFoundException(com.xpn.xwiki.user.api.XWikiRightNotFoundException) BaseObject(com.xpn.xwiki.objects.BaseObject) EntityReference(org.xwiki.model.reference.EntityReference) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) XWikiRightNotFoundException(com.xpn.xwiki.user.api.XWikiRightNotFoundException) DocumentReference(org.xwiki.model.reference.DocumentReference) HashSet(java.util.HashSet)

Example 20 with EntityReference

use of org.xwiki.model.reference.EntityReference in project xwiki-platform by xwiki.

the class ImportAction method importPackageFilterStream.

private void importPackageFilterStream(XWikiAttachment packFile, XWikiRequest request, XWikiContext context) throws IOException, XWikiException, FilterException {
    String[] pages = request.getParameterValues("pages");
    XARInputProperties xarProperties = new XARInputProperties();
    DocumentInstanceOutputProperties instanceProperties = new DocumentInstanceOutputProperties();
    instanceProperties.setSaveComment("Imported from XAR");
    if (pages != null) {
        EntityReferenceSet entities = new EntityReferenceSet();
        EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.TYPE_STRING, "relative");
        for (String pageEntry : pages) {
            if (StringUtils.isNotEmpty(pageEntry)) {
                String locale = getLocale(pageEntry, request);
                int iAction = getAction(pageEntry, locale, request);
                String documentReference = getDocumentReference(pageEntry);
                if (iAction == DocumentInfo.ACTION_OVERWRITE) {
                    entities.includes(new LocalDocumentReference(resolver.resolve(documentReference, EntityType.DOCUMENT), LocaleUtils.toLocale(locale)));
                }
            }
        }
        xarProperties.setEntities(entities);
    }
    // Set the appropriate strategy to handle versions
    if (StringUtils.equals(request.getParameter("historyStrategy"), "reset")) {
        instanceProperties.setPreviousDeleted(true);
        instanceProperties.setVersionPreserved(false);
        xarProperties.setWithHistory(false);
    } else if (StringUtils.equals(request.getParameter("historyStrategy"), "replace")) {
        instanceProperties.setPreviousDeleted(true);
        instanceProperties.setVersionPreserved(true);
        xarProperties.setWithHistory(true);
    } else {
        instanceProperties.setPreviousDeleted(false);
        instanceProperties.setVersionPreserved(false);
        xarProperties.setWithHistory(false);
    }
    // Set the backup pack option
    if (StringUtils.equals(request.getParameter("importAsBackup"), "true")) {
        instanceProperties.setAuthorPreserved(true);
    } else {
        instanceProperties.setAuthorPreserved(false);
    }
    BeanInputFilterStreamFactory<XARInputProperties> xarFilterStreamFactory = Utils.getComponent((Type) InputFilterStreamFactory.class, FilterStreamType.XWIKI_XAR_CURRENT.serialize());
    BeanInputFilterStream<XARInputProperties> xarFilterStream = xarFilterStreamFactory.createInputFilterStream(xarProperties);
    BeanOutputFilterStreamFactory<InstanceOutputProperties> instanceFilterStreamFactory = Utils.getComponent((Type) OutputFilterStreamFactory.class, FilterStreamType.XWIKI_INSTANCE.serialize());
    BeanOutputFilterStream<InstanceOutputProperties> instanceFilterStream = instanceFilterStreamFactory.createOutputFilterStream(instanceProperties);
    // Notify all the listeners about import
    ObservationManager observation = Utils.getComponent(ObservationManager.class);
    InputStream source = packFile.getContentInputStream(context);
    xarProperties.setSource(new DefaultInputStreamInputSource(source));
    // Setup log
    xarProperties.setVerbose(true);
    instanceProperties.setVerbose(true);
    instanceProperties.setStoppedWhenSaveFail(false);
    LoggerManager loggerManager = Utils.getComponent(LoggerManager.class);
    LogQueue logger = new LogQueue();
    if (loggerManager != null) {
        // Isolate log
        loggerManager.pushLogListener(new LoggerListener(UUID.randomUUID().toString(), logger));
    }
    observation.notify(new XARImportingEvent(), null, context);
    try {
        xarFilterStream.read(instanceFilterStream.getFilter());
        xarFilterStream.close();
        instanceFilterStream.close();
    } finally {
        if (loggerManager != null) {
            // Stop isolating log
            loggerManager.popLogListener();
        }
        // Print the import log
        if (LOGGER.isDebugEnabled()) {
            logger.log(LOGGER);
        } else {
            // TODO: remove when the UI show the log properly
            for (LogEvent logEvent : logger.getLogsFrom(LogLevel.ERROR)) {
                logEvent.log(LOGGER);
            }
        }
        // Close the input source
        source.close();
        observation.notify(new XARImportedEvent(), null, context);
    }
    // Generate import report
    // Emulate old packager report (for retro compatibility)
    Package oldImporter = new Package();
    if (logger.containLogsFrom(LogLevel.ERROR)) {
        context.put("install_status", DocumentInfo.INSTALL_ERROR);
    } else {
        context.put("install_status", DocumentInfo.INSTALL_OK);
    }
    EntityReferenceSerializer<String> serializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, "local");
    for (LogEvent log : logger) {
        Marker marker = log.getMarker();
        if (marker != null) {
            if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_CREATED.getName()) || marker.contains(WikiDocumentFilter.LOG_DOCUMENT_UPDATED.getName())) {
                oldImporter.getInstalled(context).add(serializer.serialize((EntityReference) log.getArgumentArray()[0]));
            } else if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_SKIPPED.getName())) {
                oldImporter.getSkipped(context).add(serializer.serialize((EntityReference) log.getArgumentArray()[0]));
            } else if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_ERROR.getName())) {
                Object entity = log.getArgumentArray()[0];
                if (entity != null) {
                    oldImporter.getErrors(context).add(entity instanceof EntityReference ? serializer.serialize((EntityReference) log.getArgumentArray()[0]) : entity.toString());
                }
            }
        }
    }
}
Also used : InstanceOutputProperties(org.xwiki.filter.instance.output.InstanceOutputProperties) DocumentInstanceOutputProperties(org.xwiki.filter.instance.output.DocumentInstanceOutputProperties) XARImportingEvent(com.xpn.xwiki.internal.event.XARImportingEvent) DefaultInputStreamInputSource(org.xwiki.filter.input.DefaultInputStreamInputSource) BeanInputFilterStreamFactory(org.xwiki.filter.input.BeanInputFilterStreamFactory) InputFilterStreamFactory(org.xwiki.filter.input.InputFilterStreamFactory) ObservationManager(org.xwiki.observation.ObservationManager) EntityReferenceSet(org.xwiki.model.reference.EntityReferenceSet) LogQueue(org.xwiki.logging.LogQueue) DocumentInstanceOutputProperties(org.xwiki.filter.instance.output.DocumentInstanceOutputProperties) EntityReference(org.xwiki.model.reference.EntityReference) LoggerManager(org.xwiki.logging.LoggerManager) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference) LogEvent(org.xwiki.logging.event.LogEvent) OutputFilterStreamFactory(org.xwiki.filter.output.OutputFilterStreamFactory) BeanOutputFilterStreamFactory(org.xwiki.filter.output.BeanOutputFilterStreamFactory) InputStream(java.io.InputStream) XARImportedEvent(com.xpn.xwiki.internal.event.XARImportedEvent) LoggerListener(org.xwiki.logging.event.LoggerListener) Marker(org.slf4j.Marker) XARInputProperties(org.xwiki.filter.xar.input.XARInputProperties) XarPackage(org.xwiki.xar.XarPackage) Package(com.xpn.xwiki.plugin.packaging.Package)

Aggregations

EntityReference (org.xwiki.model.reference.EntityReference)338 Test (org.junit.Test)157 DocumentReference (org.xwiki.model.reference.DocumentReference)107 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)39 BaseObject (com.xpn.xwiki.objects.BaseObject)38 ArrayList (java.util.ArrayList)27 XWikiContext (com.xpn.xwiki.XWikiContext)24 WikiReference (org.xwiki.model.reference.WikiReference)24 SpaceReference (org.xwiki.model.reference.SpaceReference)23 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)18 XWikiException (com.xpn.xwiki.XWikiException)17 EntityType (org.xwiki.model.EntityType)11 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)10 EntityReferenceProvider (org.xwiki.model.reference.EntityReferenceProvider)9 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)8 XDOM (org.xwiki.rendering.block.XDOM)8 URL (java.net.URL)7 AttachmentReference (org.xwiki.model.reference.AttachmentReference)7 HashMap (java.util.HashMap)6 Before (org.junit.Before)6