Search in sources :

Example 1 with VFSLeaf

use of org.olat.core.util.vfs.VFSLeaf in project OpenOLAT by OpenOLAT.

the class CmdServeResource method execute.

public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {
    VFSSecurityCallback inheritedSecCallback = VFSManager.findInheritedSecurityCallback(folderComponent.getCurrentContainer());
    if (inheritedSecCallback != null && !inheritedSecCallback.canRead())
        throw new RuntimeException("Illegal read attempt: " + folderComponent.getCurrentContainerPath());
    // extract file
    String path = ureq.getModuleURI();
    MediaResource mr = null;
    VFSItem vfsitem = folderComponent.getRootContainer().resolve(path);
    if (vfsitem == null) {
        // double decoding of ++
        vfsitem = FolderCommandHelper.tryDoubleDecoding(ureq, folderComponent);
    }
    if (vfsitem == null) {
        mr = new NotFoundMediaResource();
    } else if (!(vfsitem instanceof VFSLeaf)) {
        mr = new NotFoundMediaResource();
    } else {
        VFSLeaf vfsfile = (VFSLeaf) vfsitem;
        boolean forceDownload = FolderManager.isDownloadForcedFileType(vfsfile.getName());
        if (path.toLowerCase().endsWith(".html") || path.toLowerCase().endsWith(".htm")) {
            // setCurrentURI(path);
            // set the http content-type and the encoding
            // try to load in iso-8859-1
            InputStream is = vfsfile.getInputStream();
            if (is == null) {
                mr = new NotFoundMediaResource();
            } else {
                String page = FileUtils.load(is, DEFAULT_ENCODING);
                // search for the <meta content="text/html; charset=utf-8"
                // http-equiv="Content-Type" /> tag
                // if none found, assume iso-8859-1
                String enc = DEFAULT_ENCODING;
                boolean useLoaded = false;
                // <meta.*charset=([^"]*)"
                Matcher m = PATTERN_ENCTYPE.matcher(page);
                boolean found = m.find();
                if (found) {
                    String htmlcharset = m.group(1);
                    enc = htmlcharset;
                    if (htmlcharset.equals(DEFAULT_ENCODING)) {
                        useLoaded = true;
                    }
                } else {
                    useLoaded = true;
                }
                // set the new encoding to remember for any following .js file loads
                g_encoding = enc;
                if (useLoaded) {
                    StringMediaResource smr = new StringMediaResource();
                    String mimetype = forceDownload ? VFSMediaResource.MIME_TYPE_FORCE_DOWNLOAD : "text/html;charset=" + enc;
                    smr.setContentType(mimetype);
                    smr.setEncoding(enc);
                    smr.setData(page);
                    if (forceDownload) {
                        smr.setDownloadable(true, vfsfile.getName());
                    }
                    mr = smr;
                } else {
                    // found a new charset other than iso-8859-1 -> let it load again
                    // as bytes (so we do not need to convert to string and back
                    // again)
                    VFSMediaResource vmr = new VFSMediaResource(vfsfile);
                    vmr.setEncoding(enc);
                    if (forceDownload) {
                        vmr.setDownloadable(true);
                    }
                    mr = vmr;
                }
            }
        } else if (path.endsWith(".js")) {
            // a javascript library
            VFSMediaResource vmr = new VFSMediaResource(vfsfile);
            // that loads the .js file
            if (g_encoding != null) {
                vmr.setEncoding(g_encoding);
            }
            if (forceDownload) {
                vmr.setDownloadable(true);
            }
            mr = vmr;
        } else if (path.endsWith(".txt")) {
            // text files created in OpenOLAT are utf-8, prefer this encoding
            VFSMediaResource vmr = new VFSMediaResource(vfsfile);
            vmr.setEncoding("utf-8");
            if (forceDownload) {
                vmr.setDownloadable(true);
            }
            mr = vmr;
        } else {
            // binary data: not .html, not .htm, not .js -> treated as is
            VFSMediaResource vmr = new VFSMediaResource(vfsfile);
            if (forceDownload) {
                vmr.setDownloadable(true);
            }
            mr = vmr;
        }
    }
    ThreadLocalUserActivityLogger.log(FolderLoggingAction.BC_FILE_READ, getClass(), CoreLoggingResourceable.wrapBCFile(path));
    ureq.getDispatchResult().setResultingMediaResource(mr);
    // update download counter
    if (vfsitem instanceof MetaTagged) {
        MetaTagged itemWithMeta = (MetaTagged) vfsitem;
        MetaInfo meta = itemWithMeta.getMetaInfo();
        meta.increaseDownloadCount();
        meta.write();
    }
    return null;
}
Also used : NotFoundMediaResource(org.olat.core.gui.media.NotFoundMediaResource) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) Matcher(java.util.regex.Matcher) InputStream(java.io.InputStream) MetaTagged(org.olat.core.commons.modules.bc.meta.tagged.MetaTagged) MetaInfo(org.olat.core.commons.modules.bc.meta.MetaInfo) VFSItem(org.olat.core.util.vfs.VFSItem) StringMediaResource(org.olat.core.gui.media.StringMediaResource) MediaResource(org.olat.core.gui.media.MediaResource) NotFoundMediaResource(org.olat.core.gui.media.NotFoundMediaResource) VFSMediaResource(org.olat.core.util.vfs.VFSMediaResource) StringMediaResource(org.olat.core.gui.media.StringMediaResource) VFSSecurityCallback(org.olat.core.util.vfs.callbacks.VFSSecurityCallback) VFSMediaResource(org.olat.core.util.vfs.VFSMediaResource)

Example 2 with VFSLeaf

use of org.olat.core.util.vfs.VFSLeaf in project OpenOLAT by OpenOLAT.

the class ListRenderer method appendRenderedFile.

// getRenderedDirectoryContent
/**
 * Render a single file or folder.
 *
 * @param	f			The file or folder to render
 * @param	sb		StringOutput to append generated html code
 */
private void appendRenderedFile(FolderComponent fc, VFSItem child, String currentContainerPath, StringOutput sb, URLBuilder ubu, Translator translator, boolean iframePostEnabled, boolean canContainerVersion, int pos) {
    // assume full access unless security callback tells us something different.
    boolean canWrite = child.getParentContainer().canWrite() == VFSConstants.YES;
    // special case: virtual folders are always read only. parent of child =! the current container
    canWrite = canWrite && !(fc.getCurrentContainer() instanceof VirtualContainer);
    boolean isAbstract = (child instanceof AbstractVirtualContainer);
    Versions versions = null;
    if (canContainerVersion && child instanceof Versionable) {
        Versionable versionable = (Versionable) child;
        if (versionable.getVersions().isVersioned()) {
            versions = versionable.getVersions();
        }
    }
    boolean canVersion = versions != null && !versions.getRevisions().isEmpty();
    boolean canAddToEPortfolio = FolderConfig.isEPortfolioAddEnabled();
    VFSLeaf leaf = null;
    if (child instanceof VFSLeaf) {
        leaf = (VFSLeaf) child;
    }
    // if not a leaf, it must be a container...
    boolean isContainer = (leaf == null);
    MetaInfo metaInfo = null;
    if (child instanceof MetaTagged) {
        metaInfo = ((MetaTagged) child).getMetaInfo();
    }
    boolean lockedForUser = lockManager.isLockedForMe(child, fc.getIdentityEnvironnement().getIdentity(), fc.getIdentityEnvironnement().getRoles());
    String name = child.getName();
    boolean xssErrors = StringHelper.xssScanForErrors(name);
    String pathAndName;
    if (xssErrors) {
        pathAndName = null;
    } else {
        pathAndName = currentContainerPath;
        if (pathAndName.length() > 0 && !pathAndName.endsWith("/")) {
            pathAndName += "/";
        }
        pathAndName += name;
    }
    // tr begin
    sb.append("<tr><td>").append("<input type=\"checkbox\" name=\"").append(FileSelection.FORM_ID).append("\" value=\"");
    if (xssErrors) {
        sb.append(StringHelper.escapeHtml(name)).append("\" disabled=\"disabled\"");
    } else {
        sb.append(name).append("\" ");
    }
    sb.append("/> ");
    // browse link pre
    if (xssErrors) {
        sb.append("<i class='o_icon o_icon-fw o_icon_banned'> </i> ");
        sb.append(StringHelper.escapeHtml(name));
        log.error("XSS Scan found something suspicious in: " + child);
    } else {
        sb.append("<a id='o_sel_doc_").append(pos).append("'");
        if (isContainer) {
            // for directories... normal module URIs
            // needs encoding, not done in buildHrefAndOnclick!
            // FIXME: SR: refactor encode: move to ubu.buildHrefAndOnclick
            String pathAndNameEncoded = ubu.encodeUrl(pathAndName);
            ubu.buildHrefAndOnclick(sb, pathAndNameEncoded, iframePostEnabled, false, true);
        } else {
            // for files, add PARAM_SERV command
            sb.append(" href=\"");
            ubu.buildURI(sb, new String[] { PARAM_SERV }, new String[] { "x" }, pathAndName, AJAXFlags.MODE_NORMAL);
            sb.append("\"");
            boolean download = FolderManager.isDownloadForcedFileType(name);
            if (download) {
                sb.append(" download=\"").append(StringHelper.escapeHtml(name)).append("\"");
            } else {
                sb.append(" target=\"_blank\"");
            }
        }
        sb.append(">");
        // icon css
        sb.append("<i class=\"o_icon o_icon-fw ");
        if (isContainer)
            sb.append(CSSHelper.CSS_CLASS_FILETYPE_FOLDER);
        else
            sb.append(CSSHelper.createFiletypeIconCssClassFor(name));
        sb.append("\"></i> ");
        // name
        if (isAbstract)
            sb.append("<i>");
        sb.append(StringHelper.escapeHtml(name));
        if (isAbstract)
            sb.append("</i>");
        sb.append("</a>");
    }
    // file metadata as tooltip
    if (metaInfo != null) {
        boolean hasMeta = false;
        sb.append("<div id='o_sel_doc_tooltip_").append(pos).append("' class='o_bc_meta' style='display:none;'>");
        if (StringHelper.containsNonWhitespace(metaInfo.getTitle())) {
            String title = StringHelper.escapeHtml(metaInfo.getTitle());
            sb.append("<h5>").append(Formatter.escapeDoubleQuotes(title)).append("</h5>");
            hasMeta = true;
        }
        if (StringHelper.containsNonWhitespace(metaInfo.getComment())) {
            sb.append("<div class=\"o_comment\">");
            String comment = StringHelper.escapeHtml(metaInfo.getComment());
            sb.append(Formatter.escapeDoubleQuotes(comment));
            sb.append("</div>");
            hasMeta = true;
        }
        // boolean hasThumbnail = false;
        if (metaInfo.isThumbnailAvailable() && !xssErrors) {
            sb.append("<div class='o_thumbnail' style='background-image:url(");
            ubu.buildURI(sb, new String[] { PARAM_SERV_THUMBNAIL }, new String[] { "x" }, pathAndName, AJAXFlags.MODE_NORMAL);
            sb.append("); background-repeat:no-repeat; background-position:50% 50%;'></div>");
            hasMeta = true;
        // hasThumbnail = true;
        }
        // first try author info from metadata (creator)
        // boolean hasMetaAuthor = false;
        String author = metaInfo.getCreator();
        // fallback use file author (uploader)
        if (StringHelper.containsNonWhitespace(author)) {
        // hasMetaAuthor = true;
        } else {
            author = metaInfo.getAuthor();
            if (!"-".equals(author)) {
                author = UserManager.getInstance().getUserDisplayName(author);
            } else {
                author = null;
            }
        }
        author = StringHelper.escapeHtml(author);
        if (StringHelper.containsNonWhitespace(author)) {
            sb.append("<p class=\"o_author\">").append(Formatter.escapeDoubleQuotes(translator.translate("mf.author")));
            sb.append(": ").append(Formatter.escapeDoubleQuotes(author)).append("</p>");
            hasMeta = true;
        }
        sb.append("</div>");
        if (hasMeta) {
            // render tooltip only when it contains something
            sb.append("<script type='text/javascript'>").append("/* <![CDATA[ */").append("jQuery(function() {\n").append("  jQuery('#o_sel_doc_").append(pos).append("').tooltip({\n").append("	   html: true,\n").append("	   container: 'body',\n").append("    title: function(){ return jQuery('#o_sel_doc_tooltip_").append(pos).append("').html(); }\n").append("  });\n").append("  jQuery('#o_sel_doc_").append(pos).append("').on('click', function(){\n").append("	   jQuery('#o_sel_doc_").append(pos).append("').tooltip('hide');\n").append("  });\n").append("});").append("/* ]]> */").append("</script>");
        }
    }
    sb.append("</td><td>");
    // filesize
    if (!isContainer) {
        // append filesize
        sb.append("<span class='text-muted small'>");
        sb.append(Formatter.formatBytes(leaf.getSize()));
        sb.append("</span>");
    }
    sb.append("</td><td>");
    // last modified
    long lastModified = child.getLastModified();
    sb.append("<span class='text-muted small'>");
    if (lastModified != VFSConstants.UNDEFINED)
        sb.append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, translator.getLocale()).format(new Date(lastModified)));
    else
        sb.append("-");
    sb.append("</span></td><td>");
    // license
    if (licensesEnabled) {
        MetaInfoFactory metaInfoFactory = CoreSpringFactory.getImpl(MetaInfoFactory.class);
        License license = metaInfoFactory.getLicense(metaInfo);
        LicenseRenderer licenseRenderer = new LicenseRenderer(translator.getLocale());
        licenseRenderer.render(sb, license, true);
        sb.append("</td><td>");
    }
    if (canContainerVersion) {
        if (canVersion)
            if (versions != null) {
                sb.append("<span class='text-muted small'>");
                sb.append(versions.getRevisionNr());
                sb.append("</span>");
            }
        sb.append("</td><td>");
    }
    // locked
    boolean locked = lockManager.isLocked(child);
    if (locked) {
        LockInfo lock = lockManager.getLock(child);
        sb.append("<i class=\"o_icon o_icon_locked\" title=\"");
        if (lock != null && lock.getLockedBy() != null) {
            String fullname = userManager.getUserDisplayName(lock.getLockedBy());
            String date = "";
            if (lock.getCreationDate() != null) {
                date = fc.getDateTimeFormat().format(lock.getCreationDate());
            }
            String msg = translator.translate("Locked", new String[] { fullname, date });
            if (lock.isWebDAVLock()) {
                msg += " (WebDAV)";
            }
            sb.append(msg);
        }
        sb.append("\">&#160;</i>");
    }
    sb.append("</td><td>");
    // Info link
    if (canWrite) {
        int actionCount = 0;
        if (canVersion) {
            actionCount++;
        }
        String nameLowerCase = name.toLowerCase();
        // OO-57 only display edit link if it's not a folder
        boolean isLeaf = (child instanceof VFSLeaf);
        boolean isEditable = (isLeaf && !lockedForUser && !xssErrors && (nameLowerCase.endsWith(".html") || nameLowerCase.endsWith(".htm") || nameLowerCase.endsWith(".txt") || nameLowerCase.endsWith(".css") || nameLowerCase.endsWith(".csv	")));
        if (isEditable)
            actionCount++;
        boolean canEP = canAddToEPortfolio && !isContainer;
        if (canEP)
            actionCount++;
        boolean canMetaData = canMetaInfo(child);
        if (canMetaData)
            actionCount++;
        if (actionCount == 1 && canMetaData) {
            // when only one action is available, don't render menu
            sb.append("<a ");
            ubu.buildHrefAndOnclick(sb, null, iframePostEnabled, false, false, new NameValuePair(PARAM_EDTID, pos)).append(" title=\"").append(StringHelper.escapeHtml(translator.translate("mf.edit"))).append("\"><i class=\"o_icon o_icon-fw o_icon_edit_metadata\"></i></a>");
        } else if (actionCount > 1) {
            // add actions to menu if multiple actions available
            sb.append("<a id='o_sel_actions_").append(pos).append("' href='javascript:;'><i class='o_icon o_icon-lg o_icon_actions'></i></a>").append("<div id='o_sel_actions_pop_").append(pos).append("' style='display:none;'><ul class='list-unstyled'>");
            // meta edit action (rename etc)
            if (canMetaData) {
                // Metadata edit link... also handles rename for non-OlatRelPathImpls
                sb.append("<li><a ");
                ubu.buildHrefAndOnclick(sb, null, iframePostEnabled, false, false, new NameValuePair(PARAM_EDTID, pos)).append("><i class=\"o_icon o_icon-fw o_icon_edit_metadata\"></i> ").append(StringHelper.escapeHtml(translator.translate("mf.edit"))).append("</a></li>");
            }
            // content edit action
            if (isEditable) {
                sb.append("<li><a ");
                ubu.buildHrefAndOnclick(sb, null, iframePostEnabled, false, false, new NameValuePair(PARAM_CONTENTEDITID, pos)).append("><i class=\"o_icon o_icon-fw o_icon_edit_file\"></i> ").append(StringHelper.escapeHtml(translator.translate("editor"))).append("</a></li>");
            }
            // versions action
            if (canVersion) {
                // Versions link
                sb.append("<li><a ");
                ubu.buildHrefAndOnclick(sb, null, iframePostEnabled, false, false, new NameValuePair(PARAM_VERID, pos)).append("><i class=\"o_icon o_icon-fw o_icon_version\"></i> ").append(StringHelper.escapeHtml(translator.translate("versions"))).append("</a></li>");
            }
            // get a link for adding a file to ePortfolio, if file-owner is the current user
            if (canEP) {
                if (metaInfo != null) {
                    Identity author = metaInfo.getAuthorIdentity();
                    if (author != null && fc.getIdentityEnvironnement().getIdentity().getKey().equals(author.getKey())) {
                        sb.append("<li><a ");
                        ubu.buildHrefAndOnclick(sb, null, iframePostEnabled, false, false, new NameValuePair(PARAM_EPORT, pos)).append("><i class=\"o_icon o_icon-fw o_icon_eportfolio_add\"></i> ").append(StringHelper.escapeHtml(translator.translate("eportfolio"))).append("</a></li>");
                    }
                }
            }
            sb.append("</ul></div>").append("<script type='text/javascript'>").append("/* <![CDATA[ */").append("jQuery(function() {\n").append("  o_popover('o_sel_actions_").append(pos).append("','o_sel_actions_pop_").append(pos).append("','left');\n").append("});").append("/* ]]> */").append("</script>");
        }
    }
    sb.append("</td></tr>");
}
Also used : VFSLeaf(org.olat.core.util.vfs.VFSLeaf) NameValuePair(org.olat.core.gui.components.form.flexible.impl.NameValuePair) AbstractVirtualContainer(org.olat.core.util.vfs.AbstractVirtualContainer) MetaInfo(org.olat.core.commons.modules.bc.meta.MetaInfo) MetaTagged(org.olat.core.commons.modules.bc.meta.tagged.MetaTagged) License(org.olat.core.commons.services.license.License) MetaInfoFactory(org.olat.core.commons.modules.bc.meta.MetaInfoFactory) Date(java.util.Date) Versionable(org.olat.core.util.vfs.version.Versionable) Versions(org.olat.core.util.vfs.version.Versions) LockInfo(org.olat.core.util.vfs.lock.LockInfo) Identity(org.olat.core.id.Identity) AbstractVirtualContainer(org.olat.core.util.vfs.AbstractVirtualContainer) VirtualContainer(org.olat.core.util.vfs.VirtualContainer) LicenseRenderer(org.olat.core.commons.services.license.ui.LicenseRenderer)

Example 3 with VFSLeaf

use of org.olat.core.util.vfs.VFSLeaf in project OpenOLAT by OpenOLAT.

the class MetaInfoFileImpl method getThumbnailInfo.

private Thumbnail getThumbnailInfo(int maxWidth, int maxHeight, boolean fill) {
    for (Thumbnail thumbnail : thumbnails) {
        if (maxHeight == thumbnail.getMaxHeight() && maxWidth == thumbnail.getMaxWidth()) {
            if (thumbnail.exists()) {
                return thumbnail;
            }
        }
    }
    // generate a file name
    File metaLoc = metaFile.getParentFile();
    String name = originFile.getName();
    String extension = FileUtils.getFileSuffix(name);
    String nameOnly = name.substring(0, name.length() - extension.length() - 1);
    String randuuid = UUID.randomUUID().toString();
    String thumbnailExtension = preferedThumbnailType(extension);
    File thumbnailFile = new File(metaLoc, nameOnly + "_" + randuuid + "_" + maxHeight + "x" + maxWidth + (fill ? "xfill" : "") + "." + thumbnailExtension);
    // generate thumbnail
    long start = 0l;
    if (log.isDebug())
        start = System.currentTimeMillis();
    VFSLeaf thumbnailLeaf = new LocalFileImpl(thumbnailFile);
    VFSLeaf originLeaf = new LocalFileImpl(originFile);
    if (thumbnailService != null && thumbnailService.isThumbnailPossible(thumbnailLeaf)) {
        try {
            if (thumbnails.isEmpty()) {
                // be paranoid
                cannotGenerateThumbnail = true;
                write();
            }
            log.info("Start thumbnail: " + thumbnailLeaf);
            FinalSize finalSize = thumbnailService.generateThumbnail(originLeaf, thumbnailLeaf, maxWidth, maxHeight, fill);
            if (finalSize == null) {
                return null;
            } else {
                Thumbnail thumbnail = new Thumbnail();
                thumbnail.setMaxHeight(maxHeight);
                thumbnail.setMaxWidth(maxWidth);
                thumbnail.setFinalHeight(finalSize.getHeight());
                thumbnail.setFinalWidth(finalSize.getWidth());
                thumbnail.setFill(true);
                thumbnail.setThumbnailFile(thumbnailFile);
                thumbnails.add(thumbnail);
                cannotGenerateThumbnail = false;
                write();
                log.info("Create thumbnail: " + thumbnailLeaf);
                if (log.isDebug()) {
                    log.debug("Creation of thumbnail takes (ms): " + (System.currentTimeMillis() - start));
                }
                return thumbnail;
            }
        } catch (CannotGenerateThumbnailException e) {
            // don't try every time to create the thumbnail.
            cannotGenerateThumbnail = true;
            write();
            return null;
        }
    }
    return null;
}
Also used : VFSLeaf(org.olat.core.util.vfs.VFSLeaf) CannotGenerateThumbnailException(org.olat.core.commons.services.thumbnail.CannotGenerateThumbnailException) LocalFileImpl(org.olat.core.util.vfs.LocalFileImpl) FinalSize(org.olat.core.commons.services.thumbnail.FinalSize) File(java.io.File)

Example 4 with VFSLeaf

use of org.olat.core.util.vfs.VFSLeaf in project OpenOLAT by OpenOLAT.

the class RevisionListController method event.

@Override
protected void event(UserRequest ureq, Controller source, Event event) {
    if (source == revisionListTableCtr) {
        if (event instanceof TableEvent) {
            TableEvent tEvent = (TableEvent) event;
            int row = tEvent.getRowId();
            if (CMD_DOWNLOAD.equals(tEvent.getActionId())) {
                MediaResource resource;
                if (row < versionedFile.getVersions().getRevisions().size()) {
                    // restore current, do nothing
                    VFSRevision version = versionedFile.getVersions().getRevisions().get(row);
                    resource = new VFSRevisionMediaResource(version, true);
                } else {
                    resource = new VFSMediaResource((VFSLeaf) versionedFile);
                    ((VFSMediaResource) resource).setDownloadable(true);
                }
                ureq.getDispatchResult().setResultingMediaResource(resource);
            } else if (CMD_RESTORE.equals(tEvent.getActionId())) {
                if (row >= versionedFile.getVersions().getRevisions().size()) {
                    // restore current, do nothing
                    status = FolderCommandStatus.STATUS_SUCCESS;
                    fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED);
                } else {
                    VFSRevision version = versionedFile.getVersions().getRevisions().get(row);
                    String comment = translate("version.restore.comment", new String[] { version.getRevisionNr() });
                    if (versionedFile.getVersions().restore(ureq.getIdentity(), version, comment)) {
                        status = FolderCommandStatus.STATUS_SUCCESS;
                        fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED);
                    } else {
                        status = FolderCommandStatus.STATUS_FAILED;
                        showError("version.restore.failed");
                        fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED);
                    }
                }
            }
        } else if (event instanceof TableMultiSelectEvent) {
            TableMultiSelectEvent tEvent = (TableMultiSelectEvent) event;
            if (CMD_CANCEL.equals(tEvent.getAction())) {
                status = FolderCommandStatus.STATUS_CANCELED;
                fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED);
            } else {
                List<VFSRevision> selectedVersions = getSelectedRevisions(tEvent.getSelection());
                if (!selectedVersions.isEmpty()) {
                    if (CMD_DELETE.equals(tEvent.getAction())) {
                        String numOfVersionToDelete = Integer.toString(selectedVersions.size());
                        confirmDeleteBoxCtr = activateYesNoDialog(ureq, null, translate("version.confirmDelete", new String[] { numOfVersionToDelete }), confirmDeleteBoxCtr);
                        confirmDeleteBoxCtr.setUserObject(selectedVersions);
                    }
                }
            }
        }
    } else if (source == confirmDeleteBoxCtr) {
        if (DialogBoxUIFactory.isYesEvent(event)) {
            @SuppressWarnings("unchecked") List<VFSRevision> selectedVersions = (List<VFSRevision>) confirmDeleteBoxCtr.getUserObject();
            versionedFile.getVersions().delete(ureq.getIdentity(), selectedVersions);
            status = FolderCommandStatus.STATUS_SUCCESS;
        } else {
            status = FolderCommandStatus.STATUS_CANCELED;
        }
        fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED);
    }
}
Also used : VFSLeaf(org.olat.core.util.vfs.VFSLeaf) TableEvent(org.olat.core.gui.components.table.TableEvent) VFSRevision(org.olat.core.util.vfs.version.VFSRevision) VFSRevisionMediaResource(org.olat.core.util.vfs.VFSRevisionMediaResource) TableMultiSelectEvent(org.olat.core.gui.components.table.TableMultiSelectEvent) MediaResource(org.olat.core.gui.media.MediaResource) VFSMediaResource(org.olat.core.util.vfs.VFSMediaResource) VFSRevisionMediaResource(org.olat.core.util.vfs.VFSRevisionMediaResource) ArrayList(java.util.ArrayList) List(java.util.List) VFSMediaResource(org.olat.core.util.vfs.VFSMediaResource)

Example 5 with VFSLeaf

use of org.olat.core.util.vfs.VFSLeaf in project OpenOLAT by OpenOLAT.

the class CmdUnzip method execute.

public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {
    this.translator = trans;
    FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
    VFSContainer currentContainer = folderComponent.getCurrentContainer();
    if (!(currentContainer.canWrite() == VFSConstants.YES))
        throw new AssertException("Cannot unzip to folder. Writing denied.");
    // check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name
    if (selection.getInvalidFileNames().size() > 0) {
        status = FolderCommandStatus.STATUS_INVALID_NAME;
        return null;
    }
    List<String> lockedFiles = new ArrayList<String>();
    for (String sItem : selection.getFiles()) {
        VFSItem vfsItem = currentContainer.resolve(sItem);
        if (vfsItem instanceof VFSLeaf) {
            try {
                Roles roles = ureq.getUserSession().getRoles();
                lockedFiles.addAll(checkLockedFiles((VFSLeaf) vfsItem, currentContainer, ureq.getIdentity(), roles));
            } catch (Exception e) {
                String name = vfsItem == null ? "NULL" : vfsItem.getName();
                getWindowControl().setError(translator.translate("FileUnzipFailed", new String[] { name }));
            }
        }
    }
    if (!lockedFiles.isEmpty()) {
        String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
        List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
        lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
        return null;
    }
    VFSItem currentVfsItem = null;
    try {
        boolean fileNotExist = false;
        for (String sItem : selection.getFiles()) {
            currentVfsItem = currentContainer.resolve(sItem);
            if (currentVfsItem != null && (currentVfsItem instanceof VFSLeaf)) {
                if (!doUnzip((VFSLeaf) currentVfsItem, currentContainer, ureq, wContr)) {
                    status = FolderCommandStatus.STATUS_FAILED;
                    break;
                }
            } else {
                fileNotExist = true;
                break;
            }
        }
        if (fileNotExist) {
            status = FolderCommandStatus.STATUS_FAILED;
            getWindowControl().setError(translator.translate("FileDoesNotExist"));
        }
        VFSContainer inheritingCont = VFSManager.findInheritingSecurityCallbackContainer(folderComponent.getRootContainer());
        if (inheritingCont != null) {
            VFSSecurityCallback secCallback = inheritingCont.getLocalSecurityCallback();
            if (secCallback != null) {
                SubscriptionContext subsContext = secCallback.getSubscriptionContext();
                if (subsContext != null) {
                    NotificationsManager.getInstance().markPublisherNews(subsContext, ureq.getIdentity(), true);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        logError("Corrupted ZIP", e);
        String name = currentVfsItem == null ? "NULL" : currentVfsItem.getName();
        getWindowControl().setError(translator.translate("FileUnzipFailed", new String[] { name }));
    }
    return null;
}
Also used : FileSelection(org.olat.core.commons.modules.bc.FileSelection) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) AssertException(org.olat.core.logging.AssertException) VFSContainer(org.olat.core.util.vfs.VFSContainer) ArrayList(java.util.ArrayList) VFSItem(org.olat.core.util.vfs.VFSItem) Roles(org.olat.core.id.Roles) AssertException(org.olat.core.logging.AssertException) SubscriptionContext(org.olat.core.commons.services.notifications.SubscriptionContext) VFSSecurityCallback(org.olat.core.util.vfs.callbacks.VFSSecurityCallback)

Aggregations

VFSLeaf (org.olat.core.util.vfs.VFSLeaf)642 VFSContainer (org.olat.core.util.vfs.VFSContainer)338 VFSItem (org.olat.core.util.vfs.VFSItem)280 File (java.io.File)114 InputStream (java.io.InputStream)96 IOException (java.io.IOException)92 Test (org.junit.Test)86 ArrayList (java.util.ArrayList)72 OutputStream (java.io.OutputStream)60 MetaInfo (org.olat.core.commons.modules.bc.meta.MetaInfo)58 MetaTagged (org.olat.core.commons.modules.bc.meta.tagged.MetaTagged)58 OlatRootFolderImpl (org.olat.core.commons.modules.bc.vfs.OlatRootFolderImpl)58 Identity (org.olat.core.id.Identity)54 LocalFileImpl (org.olat.core.util.vfs.LocalFileImpl)52 VFSMediaResource (org.olat.core.util.vfs.VFSMediaResource)46 URL (java.net.URL)40 Date (java.util.Date)40 RepositoryEntry (org.olat.repository.RepositoryEntry)36 URI (java.net.URI)34 MediaResource (org.olat.core.gui.media.MediaResource)34