Search in sources :

Example 71 with DocumentReference

use of org.xwiki.model.reference.DocumentReference 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 72 with DocumentReference

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

the class ExportAction method exportHTML.

/**
 * Create ZIP archive containing wiki pages rendered in HTML, attached files and used skins.
 *
 * @param context the XWiki context.
 * @return always return null.
 * @throws XWikiException error when exporting HTML ZIP package.
 * @throws IOException error when exporting HTML ZIP package.
 * @since XWiki Platform 1.3M1
 */
private String exportHTML(XWikiContext context) throws XWikiException, IOException {
    XWikiRequest request = context.getRequest();
    String description = request.get("description");
    String name = request.get("name");
    if (StringUtils.isBlank(name)) {
        name = context.getDoc().getFullName();
    }
    Collection<DocumentReference> pageList = resolvePagesToExport(request.getParameterValues("pages"), context);
    if (pageList.isEmpty()) {
        return null;
    }
    HtmlPackager packager = new HtmlPackager();
    if (name != null && name.trim().length() > 0) {
        packager.setName(name);
    }
    if (description != null) {
        packager.setDescription(description);
    }
    packager.addPageReferences(pageList);
    packager.export(context);
    return null;
}
Also used : HtmlPackager(com.xpn.xwiki.export.html.HtmlPackager) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 73 with DocumentReference

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

the class ExportAction method exportXAR.

private String exportXAR(XWikiContext context) throws XWikiException, IOException, FilterException {
    XWikiRequest request = context.getRequest();
    boolean history = Boolean.valueOf(request.get("history"));
    boolean backup = Boolean.valueOf(request.get("backup"));
    String author = request.get("author");
    String description = request.get("description");
    String licence = request.get("licence");
    String version = request.get("version");
    String name = request.get("name");
    String[] pages = request.getParameterValues("pages");
    boolean all = ArrayUtils.isEmpty(pages);
    if (!context.getWiki().getRightService().hasWikiAdminRights(context)) {
        context.put("message", "needadminrights");
        return "exception";
    }
    if (StringUtils.isEmpty(name)) {
        if (all) {
            name = "backup";
        } else {
            name = "export";
        }
    }
    if (context.getWiki().ParamAsLong("xwiki.action.export.xar.usefilter", 1) == 1) {
        // Create input wiki stream
        DocumentInstanceInputProperties inputProperties = new DocumentInstanceInputProperties();
        // We don't want to log the details
        inputProperties.setVerbose(false);
        inputProperties.setWithJRCSRevisions(history);
        inputProperties.setWithRevisions(false);
        EntityReferenceSet entities = new EntityReferenceSet();
        if (all) {
            entities.includes(new WikiReference(context.getWikiId()));
        } else {
            // Find all page references and add them for processing
            Collection<DocumentReference> pageList = resolvePagesToExport(pages, context);
            for (DocumentReference page : pageList) {
                entities.includes(page);
            }
        }
        inputProperties.setEntities(entities);
        InputFilterStreamFactory inputFilterStreamFactory = Utils.getComponent(InputFilterStreamFactory.class, FilterStreamType.XWIKI_INSTANCE.serialize());
        InputFilterStream inputFilterStream = inputFilterStreamFactory.createInputFilterStream(inputProperties);
        // Create output wiki stream
        XAROutputProperties xarProperties = new XAROutputProperties();
        // We don't want to log the details
        xarProperties.setVerbose(false);
        XWikiResponse response = context.getResponse();
        xarProperties.setTarget(new DefaultOutputStreamOutputTarget(response.getOutputStream()));
        xarProperties.setPackageName(name);
        if (description != null) {
            xarProperties.setPackageDescription(description);
        }
        if (licence != null) {
            xarProperties.setPackageLicense(licence);
        }
        if (author != null) {
            xarProperties.setPackageAuthor(author);
        }
        if (version != null) {
            xarProperties.setPackageVersion(version);
        }
        xarProperties.setPackageBackupPack(backup);
        xarProperties.setPreserveVersion(backup || history);
        BeanOutputFilterStreamFactory<XAROutputProperties> xarFilterStreamFactory = Utils.getComponent((Type) OutputFilterStreamFactory.class, FilterStreamType.XWIKI_XAR_CURRENT.serialize());
        OutputFilterStream outputFilterStream = xarFilterStreamFactory.createOutputFilterStream(xarProperties);
        // Export
        response.setContentType("application/zip");
        response.addHeader("Content-disposition", "attachment; filename=" + Util.encodeURI(name, context) + ".xar");
        inputFilterStream.read(outputFilterStream.getFilter());
        inputFilterStream.close();
        outputFilterStream.close();
        // Flush
        response.getOutputStream().flush();
        // Indicate that we are done with the response so no need to add anything
        context.setFinished(true);
    } else {
        PackageAPI export = ((PackageAPI) context.getWiki().getPluginApi("package", context));
        if (export == null) {
            // No Packaging plugin configured
            return "exception";
        }
        export.setWithVersions(history);
        if (author != null) {
            export.setAuthorName(author);
        }
        if (description != null) {
            export.setDescription(description);
        }
        if (licence != null) {
            export.setLicence(licence);
        }
        if (version != null) {
            export.setVersion(version);
        }
        export.setBackupPack(backup);
        export.setName(name);
        if (all) {
            export.backupWiki();
        } else {
            if (pages != null) {
                for (String pageName : pages) {
                    String defaultAction = request.get("action_" + pageName);
                    int iAction;
                    try {
                        iAction = Integer.parseInt(defaultAction);
                    } catch (Exception e) {
                        iAction = 0;
                    }
                    export.add(pageName, iAction);
                }
            }
            export.export();
        }
    }
    return null;
}
Also used : PackageAPI(com.xpn.xwiki.plugin.packaging.PackageAPI) OutputFilterStreamFactory(org.xwiki.filter.output.OutputFilterStreamFactory) BeanOutputFilterStreamFactory(org.xwiki.filter.output.BeanOutputFilterStreamFactory) InputFilterStreamFactory(org.xwiki.filter.input.InputFilterStreamFactory) OutputFilterStream(org.xwiki.filter.output.OutputFilterStream) DefaultOutputStreamOutputTarget(org.xwiki.filter.output.DefaultOutputStreamOutputTarget) InputFilterStream(org.xwiki.filter.input.InputFilterStream) XAROutputProperties(org.xwiki.filter.xar.output.XAROutputProperties) XWikiException(com.xpn.xwiki.XWikiException) QueryException(org.xwiki.query.QueryException) IOException(java.io.IOException) FilterException(org.xwiki.filter.FilterException) EntityReferenceSet(org.xwiki.model.reference.EntityReferenceSet) DocumentInstanceInputProperties(org.xwiki.filter.instance.input.DocumentInstanceInputProperties) WikiReference(org.xwiki.model.reference.WikiReference) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 74 with DocumentReference

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

the class ExportURLFactory method renderWithSkinAction.

private void renderWithSkinAction(String spaces, String name, String wikiId, String path, XWikiContext context) throws IOException, XWikiException {
    // We're simulating a Skin Action below. However we need to ensure that we set the right doc
    // in the XWiki Context since this is what XWikiAction does and if we don't do this it generates
    // issues since the current doc is put in the context instead of the skin. Specifically we'll
    // get for example "Main.WebHome" as the current doc instead of "Main.flamingo".
    // See https://jira.xwiki.org/browse/XWIKI-10922 for details.
    DocumentReference dummyDocumentReference = new DocumentReference(wikiId, this.legacySpaceResolver.resolve(spaces), name);
    XWikiDocument dummyDocument = context.getWiki().getDocument(dummyDocumentReference, context);
    Map<String, Object> backup = new HashMap<>();
    XWikiDocument.backupContext(backup, context);
    try {
        dummyDocument.setAsContextDoc(context);
        SKINACTION.render(path, context);
    } finally {
        XWikiDocument.restoreContext(backup, context);
    }
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) HashMap(java.util.HashMap) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 75 with DocumentReference

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

the class ExportURLFactory method createURL.

@Override
public URL createURL(String spaces, String name, String action, String querystring, String anchor, String xwikidb, XWikiContext context) {
    try {
        // Look for a special handler for the passed action
        try {
            ExportURLFactoryActionHandler handler = Utils.getComponent(ExportURLFactoryActionHandler.class, action);
            return handler.createURL(spaces, name, querystring, anchor, xwikidb, context, getFilesystemExportContext());
        } catch (Exception e) {
        // Failed to find such a component or it doesn't work, simply ignore it and continue with the default
        // behavior!
        }
        String wikiname = xwikidb == null ? context.getWikiId().toLowerCase() : xwikidb.toLowerCase();
        String serializedReference = this.fsPathEntityReferenceSerializer.serialize(new DocumentReference(wikiname, this.legacySpaceResolver.resolve(spaces), name));
        if (getFilesystemExportContext().hasExportedPage(serializedReference) && "view".equals(action) && context.getLinksAction() == null) {
            StringBuffer newpath = new StringBuffer();
            newpath.append("file://");
            // Adjust depending on the exported location of the current doc.
            newpath.append(StringUtils.repeat("../", getFilesystemExportContext().getDocParentLevel()));
            newpath.append("pages/");
            // Compute a valid relative URL from a FS path.
            String relativeURLPath = new File("").toURI().relativize(new File(serializedReference).toURI()).toString();
            newpath.append(relativeURLPath);
            newpath.append(".html");
            if (!StringUtils.isEmpty(anchor)) {
                newpath.append("#");
                newpath.append(anchor);
            }
            return new URL(newpath.toString());
        }
    } catch (Exception e) {
        LOGGER.error("Failed to create page URL", e);
    }
    return super.createURL(spaces, name, action, querystring, anchor, xwikidb, context);
}
Also used : File(java.io.File) XWikiException(com.xpn.xwiki.XWikiException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DocumentReference(org.xwiki.model.reference.DocumentReference) URL(java.net.URL)

Aggregations

DocumentReference (org.xwiki.model.reference.DocumentReference)1324 Test (org.junit.Test)711 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)482 BaseObject (com.xpn.xwiki.objects.BaseObject)250 XWikiContext (com.xpn.xwiki.XWikiContext)186 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)157 ArrayList (java.util.ArrayList)128 WikiReference (org.xwiki.model.reference.WikiReference)127 XWikiException (com.xpn.xwiki.XWikiException)121 EntityReference (org.xwiki.model.reference.EntityReference)113 SpaceReference (org.xwiki.model.reference.SpaceReference)96 XWiki (com.xpn.xwiki.XWiki)82 HashMap (java.util.HashMap)54 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)52 Expectations (org.jmock.Expectations)50 Before (org.junit.Before)50 DocumentModelBridge (org.xwiki.bridge.DocumentModelBridge)46 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)45 AttachmentReference (org.xwiki.model.reference.AttachmentReference)44 Date (java.util.Date)42