Search in sources :

Example 6 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class DeleteAttachmentAction method action.

@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }
    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiAttachment attachment = null;
    XWiki xwiki = context.getWiki();
    String filename;
    // Delete from the trash
    if (request.getParameter("trashId") != null) {
        long trashId = NumberUtils.toLong(request.getParameter("trashId"));
        DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context, true);
        // don't try to delete it and instead redirect to the attachment list.
        if (da != null) {
            com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context);
            if (!daapi.canDelete()) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "You are not allowed to delete an attachment from the trash " + "immediately after it has been deleted from the wiki");
            }
            if (!da.getDocName().equals(doc.getFullName())) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION, "The specified trash entry does not match the current document");
            }
            // TODO: Add a confirmation check
            xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true);
        }
        sendRedirect(response, Utils.getRedirect("attach", context));
        return false;
    }
    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        // Note: We use getRequestURI() because the spec says the server doesn't decode it, as
        // we want to use our own decoding.
        String requestUri = request.getRequestURI();
        filename = getFileName();
    }
    XWikiDocument newdoc = doc.clone();
    // An attachment can be indicated either using an id, or using the filename.
    if (request.getParameter("id") != null) {
        int id = NumberUtils.toInt(request.getParameter("id"));
        if (newdoc.getAttachmentList().size() > id) {
            attachment = newdoc.getAttachmentList().get(id);
        }
    } else {
        attachment = newdoc.getAttachment(filename);
    }
    // No such attachment
    if (attachment == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ScriptContext scriptContext = getCurrentScriptContext();
        if (scriptContext != null) {
            scriptContext.setAttribute("message", localizePlainOrKey("core.action.deleteAttachment.failed", filename), ScriptContext.ENGINE_SCOPE);
            scriptContext.setAttribute("details", localizePlainOrKey("platform.core.action.deleteAttachment.noAttachment"), ScriptContext.ENGINE_SCOPE);
        }
        return true;
    }
    newdoc.setAuthorReference(context.getUserReference());
    // Set "deleted attachment" as the version comment.
    String comment;
    if (attachment.isImage(context)) {
        comment = localizePlainOrKey("core.comment.deleteImageComment", filename);
    } else {
        comment = localizePlainOrKey("core.comment.deleteAttachmentComment", filename);
    }
    try {
        newdoc.removeAttachment(attachment);
        xwiki.saveDocument(newdoc, comment, context);
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ScriptContext scriptContext = getCurrentScriptContext();
        if (scriptContext != null) {
            scriptContext.setAttribute("message", localizePlainOrKey("core.action.deleteAttachment.failed", filename), ScriptContext.ENGINE_SCOPE);
            scriptContext.setAttribute("details", ExceptionUtils.getRootCauseMessage(ex), ScriptContext.ENGINE_SCOPE);
        }
        return true;
    }
    // forward to attach page
    if (!((Boolean) context.get("ajax")).booleanValue()) {
        String redirect = Utils.getRedirect("attach", context);
        sendRedirect(response, redirect);
    }
    return false;
}
Also used : XWiki(com.xpn.xwiki.XWiki) ScriptContext(javax.script.ScriptContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) DeletedAttachment(com.xpn.xwiki.doc.DeletedAttachment) XWikiException(com.xpn.xwiki.XWikiException) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException)

Example 7 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class DownloadAction method getAttachment.

private XWikiAttachment getAttachment(XWikiRequest request, XWikiDocument document, String filename) {
    XWikiAttachment attachment = null;
    String idStr = request.getParameter("id");
    if (StringUtils.isNumeric(idStr)) {
        int id = Integer.parseInt(idStr);
        if (document.getAttachmentList().size() > id) {
            attachment = document.getAttachmentList().get(id);
        }
    } else {
        attachment = document.getAttachment(filename);
    }
    return attachment;
}
Also used : XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment)

Example 8 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class ExtensionVersionFileRESTResource method downloadLocalExtension.

private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion) throws ResolveException, IOException, QueryException, XWikiException {
    XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId);
    checkRights(extensionDocument);
    ResourceReference resourceReference = repositoryManager.getDownloadReference(extensionDocument, extensionVersion);
    ResponseBuilder response = null;
    if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) {
        // It's an attachment
        AttachmentReference attachmentReference = this.attachmentResolver.resolve(resourceReference.getReference(), extensionDocument.getDocumentReference());
        XWikiContext xcontext = getXWikiContext();
        XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext);
        checkRights(document);
        XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName());
        response = getAttachmentResponse(xwikiAttachment);
    } else if (ResourceType.URL.equals(resourceReference.getType())) {
        // It's an URL
        URL url = new URL(resourceReference.getReference());
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository");
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        httpClient.setRoutePlanner(routePlanner);
        HttpGet getMethod = new HttpGet(url.toString());
        HttpResponse subResponse;
        try {
            subResponse = httpClient.execute(getMethod);
        } catch (Exception e) {
            throw new IOException("Failed to request [" + getMethod.getURI() + "]", e);
        }
        response = Response.status(subResponse.getStatusLine().getStatusCode());
        // TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes.
        // Should probably use javax.ws.rs.ext.MessageBodyWriter
        HttpEntity entity = subResponse.getEntity();
        InputRepresentation content = new InputRepresentation(entity.getContent(), entity.getContentType() != null ? new MediaType(entity.getContentType().getValue()) : MediaType.APPLICATION_OCTET_STREAM, entity.getContentLength());
        BaseObject extensionObject = getExtensionObject(extensionDocument);
        String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);
        Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type);
        content.setDisposition(disposition);
        response.entity(content);
    } else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) {
        ExtensionResourceReference extensionResource;
        if (resourceReference instanceof ExtensionResourceReference) {
            extensionResource = (ExtensionResourceReference) resourceReference;
        } else {
            extensionResource = new ExtensionResourceReference(resourceReference.getReference());
        }
        response = downloadRemoteExtension(extensionResource);
    } else {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    return response;
}
Also used : AttachmentReference(org.xwiki.model.reference.AttachmentReference) HttpEntity(org.apache.http.HttpEntity) InputRepresentation(org.restlet.representation.InputRepresentation) WebApplicationException(javax.ws.rs.WebApplicationException) HttpGet(org.apache.http.client.methods.HttpGet) XWikiContext(com.xpn.xwiki.XWikiContext) HttpResponse(org.apache.http.HttpResponse) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) IOException(java.io.IOException) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) XWikiException(com.xpn.xwiki.XWikiException) URISyntaxException(java.net.URISyntaxException) WebApplicationException(javax.ws.rs.WebApplicationException) QueryException(org.xwiki.query.QueryException) IOException(java.io.IOException) ResolveException(org.xwiki.extension.ResolveException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ProxySelectorRoutePlanner(org.apache.http.impl.conn.ProxySelectorRoutePlanner) Disposition(org.restlet.data.Disposition) MediaType(org.restlet.data.MediaType) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference)

Example 9 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class FilesystemAttachmentStore method saveAttachmentsContent.

/**
 * {@inheritDoc}
 * <p>
 * This implementation cannot operate in a larger transaction so it starts a new transaction no matter whether
 * bTransaction is true or false.
 * </p>
 *
 * @see com.xpn.xwiki.store.XWikiAttachmentStoreInterface#saveAttachmentsContent( List, XWikiDocument, boolean,
 *      XWikiContext, boolean)
 */
@Override
public void saveAttachmentsContent(final List<XWikiAttachment> attachments, final XWikiDocument doc, final boolean updateDocument, final XWikiContext context, final boolean bTransaction) throws XWikiException {
    if (attachments == null || attachments.isEmpty()) {
        return;
    }
    try {
        final XWikiHibernateTransaction transaction = new XWikiHibernateTransaction(context);
        for (XWikiAttachment attach : attachments) {
            this.getAttachmentContentSaveRunnable(attach, false, context).runIn(transaction);
        }
        // Save the parent document only once.
        if (updateDocument) {
            new TransactionRunnable<XWikiHibernateTransaction>() {

                @Override
                protected void onRun() throws Exception {
                    context.getWiki().getStore().saveXWikiDoc(doc, context, false);
                }
            }.runIn(transaction);
        }
        transaction.start();
    } catch (XWikiException e) {
        throw e;
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT, "Exception while saving attachments", e);
    }
}
Also used : XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiException(com.xpn.xwiki.XWikiException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) XWikiException(com.xpn.xwiki.XWikiException)

Example 10 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class FilesystemAttachmentVersioningStore method loadArchive.

/**
 * Load an attachment archive from a specified location.
 *
 * @param attachment the attachment to load the archive for.
 * @param provider a means of gaining access to the location where the archive is stored.
 * @return an XWikiAttachmentArchive for the given attachment.
 * @throws IOException if the metadata cannot be found or there is a failure while parsing it.
 */
XWikiAttachmentArchive loadArchive(final XWikiAttachment attachment, final AttachmentFileProvider provider) throws IOException {
    final File metaFile = provider.getAttachmentVersioningMetaFile();
    // If no meta file then assume no archive and return an empty archive.
    if (!metaFile.exists()) {
        return new ListAttachmentArchive(attachment);
    }
    final ReadWriteLock lock = this.fileTools.getLockForFile(metaFile);
    final List<XWikiAttachment> attachList;
    lock.readLock().lock();
    try {
        final InputStream is = new FileInputStream(metaFile);
        attachList = this.metaSerializer.parse(is);
        is.close();
    } finally {
        lock.readLock().unlock();
    }
    // Get the content file and lock for each revision.
    for (XWikiAttachment attach : attachList) {
        final File contentFile = provider.getAttachmentVersionContentFile(attach.getVersion());
        attach.setAttachment_content(new FilesystemAttachmentContent(contentFile, attach));
        attach.setContentStore(FileSystemStoreUtils.HINT);
        // Pass the document since it will be lost in the serialize/deserialize.
        attach.setDoc(attachment.getDoc());
    }
    final ListAttachmentArchive out = new ListAttachmentArchive(attachList);
    out.setAttachment(attachment);
    return out;
}
Also used : FilesystemAttachmentContent(org.xwiki.store.legacy.doc.internal.FilesystemAttachmentContent) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) File(java.io.File) ListAttachmentArchive(org.xwiki.store.legacy.doc.internal.ListAttachmentArchive) FileInputStream(java.io.FileInputStream)

Aggregations

XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)133 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)71 DocumentReference (org.xwiki.model.reference.DocumentReference)51 Test (org.junit.Test)40 XWikiContext (com.xpn.xwiki.XWikiContext)35 XWikiException (com.xpn.xwiki.XWikiException)25 ByteArrayInputStream (java.io.ByteArrayInputStream)20 Attachment (com.xpn.xwiki.api.Attachment)18 Date (java.util.Date)17 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)15 Document (com.xpn.xwiki.api.Document)14 XWiki (com.xpn.xwiki.XWiki)13 BaseObject (com.xpn.xwiki.objects.BaseObject)13 AttachmentReference (org.xwiki.model.reference.AttachmentReference)13 InputStream (java.io.InputStream)11 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)10 File (java.io.File)10 URL (java.net.URL)7 List (java.util.List)7