Package com.dotmarketing.business

Examples of com.dotmarketing.business.PermissionAPI


    ActionRequestImpl reqImpl = (ActionRequestImpl) req;
    HttpServletRequest httpReq = reqImpl.getHttpServletRequest();

    WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
 
    PermissionAPI perAPI = APILocator.getPermissionAPI();

    // Checking permissions
    if (!perAPI.doesUserHavePermission(webAsset, PERMISSION_WRITE, user)) {
      Logger.debug(DotPortletAction.class, "_checkUserPermissions: user does not have permissions ( " + PERMISSION_WRITE + " ) over this asset: " + webAsset);
      List<Role> roles = perAPI.getRoles(webAsset.getPermissionId(), PermissionAPI.PERMISSION_PUBLISH, "CMS Owner", 0, -1);
     
      Role cmsOwner = APILocator.getRoleAPI().loadCMSOwnerRole();
      boolean isCMSOwner = false;
      if(roles.size() > 0){
        for (Role role : roles) {
View Full Code Here


      return forward;
    }
  }

  protected static void _checkUserPermissions(Inode webAsset, User user, int permission) throws ActionException, DotDataException {
    PermissionAPI perAPI = APILocator.getPermissionAPI();
    // Checking permissions
    if (!InodeUtils.isSet(webAsset.getInode()))
      return;
    if (!perAPI.doesUserHavePermission(webAsset, permission, user)) {
      Logger.debug(DotPortletAction.class, "_checkUserPermissions: user does not have permissions ( " + permission + " ) over this asset: " + webAsset);
      List<Role> rolesPublish = perAPI.getRoles(webAsset.getInode(), PermissionAPI.PERMISSION_PUBLISH, "CMS Owner", 0, -1);
      List<Role> rolesWrite = perAPI.getRoles(webAsset.getInode(), PermissionAPI.PERMISSION_WRITE, "CMS Owner", 0, -1);
     
      Role cmsOwner;
      try {
        cmsOwner = APILocator.getRoleAPI().loadCMSOwnerRole();
      } catch (DotDataException e) {
View Full Code Here

      throw ae;
    }
  }

  protected void _copyPermissions(Inode from, Inode to) throws ActionException, DotDataException {
    PermissionAPI perAPI = APILocator.getPermissionAPI();
    perAPI.copyPermissions(from, to);
  }
View Full Code Here

   * @throws DotDataException
   * @throws DotSecurityException
   * @throws DotStateException
   */
  public boolean canUserPublish(String pageId, boolean respectedFrontendRoles) throws DotDataException, DotStateException, DotSecurityException{
    PermissionAPI perAPI = APILocator.getPermissionAPI();
    Identifier pageIdentifier;
    try {
      pageIdentifier = APILocator.getIdentifierAPI().find(pageId);
    } catch (DotHibernateException e) {
      Logger.error("Unable to retrieve identifier : ",e.getMessage() ,e);
      return false;
    }
    HTMLPage page = (HTMLPage)APILocator.getVersionableAPI().findWorkingVersion(pageIdentifier,APILocator.getUserAPI().getSystemUser(),false);
   
    /*Identifier ident = (Identifier)CacheLocator.getIdentifierCache().removeFromCacheByVersionable(pageInode);
    HTMLPage page = HTMLPageFactory.*/
    //System.out.println(perAPI.doesUserHavePermission(page, PermissionAPI.PERMISSION_PUBLISH, user, false));
    return perAPI.doesUserHavePermission(page, PermissionAPI.PERMISSION_PUBLISH, backuser, false);
  }
View Full Code Here

      }

    }

    List<Versionable> files = new ArrayList<Versionable>();
    PermissionAPI perAPI = APILocator.getPermissionAPI();
    try {

      if (parent == null) {

        // Getting the files directly under the host
        files.addAll(APILocator.getFileAssetAPI().findFileAssetsByHost(host, user, !showWorking, showWorking, false, false));
        if(showArchived)
          files.addAll(APILocator.getFileAssetAPI().findFileAssetsByHost(host, user, !showWorking, showWorking, showArchived, false));

      } else {
            ChildrenCondition cond = new ChildrenCondition();
            if(showWorking)
              cond.working = true;
            else
              cond.live = true;
        files.addAll(folderAPI.getFiles(parent,  userAPI.getSystemUser(), false, cond));
        if (showArchived) {
          cond.deleted = showArchived;
          files.addAll(folderAPI.getFiles(parent, userAPI.getSystemUser(), false, cond));
        }
        files.addAll(APILocator.getFileAssetAPI().findFileAssetsByFolder(parent, "", !showWorking, showWorking, user, false));
      }

      //remove duplicated legacy files from list. See issue 5943
    HashSet<Versionable> tempFilesListToSet = new HashSet<Versionable>(files);
    files.clear();
    files.addAll(tempFilesListToSet);

    } catch (Exception e2) {
      Logger.error(this, "Could not load files : ", e2);
    }

    Contentlet contentlet;
    WorkflowStep wfStep;
    WorkflowScheme wfScheme = null;

    for (Versionable file : files) {

      if (file == null)
        continue;

      List<Integer> permissions = new ArrayList<Integer>();
      try {
        permissions = permissionAPI.getPermissionIdsFromRoles(
            (Permissionable) file, roles, user);
      } catch (DotDataException e) {
        Logger.error(this, "Could not load permissions : ", e);
      }

      List<WorkflowAction> wfActions = new ArrayList<WorkflowAction>();

      contentlet = null;
      if (file instanceof com.dotmarketing.portlets.fileassets.business.FileAsset)
        contentlet = (Contentlet) file;
      try {
        if (contentlet != null) {
          wfStep = APILocator.getWorkflowAPI().findStepByContentlet(
              contentlet);
          wfScheme = APILocator.getWorkflowAPI().findScheme(
              wfStep.getSchemeId());
          wfActions = APILocator.getWorkflowAPI()
              .findAvailableActions(contentlet, user);
        }
      } catch (Exception e) {
        Logger.error(this, "Could not load workflow actions : ", e);
        // wfActions = new ArrayList();
      }
      boolean contentEditable = false;
      if (contentlet != null) {
        if (perAPI.doesUserHavePermission(contentlet,
            PermissionAPI.PERMISSION_WRITE, user)
            && contentlet.isLocked()) {
          String lockedUserId = APILocator.getVersionableAPI()
              .getLockedBy(contentlet);
          if (user.getUserId().equals(lockedUserId)) {
View Full Code Here

   * @throws ValidationException
   * @throws DotDataException
   */
  public static List<Map<String, Serializable>> DBSearch(Query query, Map<String, String> dbColToObjectAttribute, String conditionToAppend, User user,boolean isPermissionsByIdentifier,boolean respectFrontendRoles) throws ValidationException,DotDataException{
    Map<String, String> objectAttributeTodbCol = new HashMap<String, String>();
      PermissionAPI perAPI = APILocator.getPermissionAPI();
    for (String key : dbColToObjectAttribute.keySet()) {
      objectAttributeTodbCol.put(dbColToObjectAttribute.get(key), key);
    }
    List<Map<String, Serializable>> res = new ArrayList<Map<String,Serializable>>();
    List<Map<String, Serializable>> filteredResults = new ArrayList<Map<String,Serializable>>();
    Criteria c = query.getCriteria();
    StringBuilder bob = new StringBuilder();
    List<Object> params = null;
    List <PermissionableProxy> permDummys= new  ArrayList <PermissionableProxy> ();
    bob.append("SELECT ");   
    if(UtilMethods.isSet(query.getSelectAttributes())){
      boolean first = true;
      for (String att : query.getSelectAttributes()) {
        if(!first){
          bob.append(",");
        }
        if(objectAttributeTodbCol.get(att) != null){
          bob.append(query.getBuilderType()+"."+objectAttributeTodbCol.get(att));
        }else{
          bob.append(query.getBuilderType()+"."+att);
        }
        first = false;
      }
    }else{
      bob.append(query.getBuilderType()+".*");
    }
    String queryBuilderType = query.getBuilderType().toString();
    if(queryBuilderType.equalsIgnoreCase(BuilderType.CONTENTLET.toString())
        || queryBuilderType.equalsIgnoreCase(BuilderType.FILE_ASSET.toString())
        || queryBuilderType.equalsIgnoreCase(BuilderType.HTMLPAGE.toString())
        || queryBuilderType.equalsIgnoreCase(BuilderType.MENU_LINK.toString())){   
      bob.append(","+queryBuilderType+".identifier,inode.owner");
    }else{
      bob.append(",inode.owner");
    }
    bob.append(" FROM " + query.getBuilderType()+", inode");
    if(UtilMethods.isSet(conditionToAppend)){
       bob.append(" WHERE " + conditionToAppend);
    }
    if(c != null){
      params = new ArrayList<Object>();
      if(!UtilMethods.isSet(conditionToAppend)){
        bob.append(" WHERE ");
      }else{
        bob.append(" AND ");
      }
      if(c instanceof SimpleCriteria){ 
        String att = objectAttributeTodbCol.get(((SimpleCriteria) c).getAttribute()) != null ? objectAttributeTodbCol.get(((SimpleCriteria) c).getAttribute()) : ((SimpleCriteria) c).getAttribute();
        bob.append(att + " " + ((SimpleCriteria) c).getOperator() + " ?");
        params.add(((SimpleCriteria) c).getValue());
      }else if(c instanceof ComplexCriteria){
        List<Criteria> criteriaList = ((ComplexCriteria) c).getCriteria();
        boolean open = false;
        for (Criteria criteria : criteriaList) {
          if(criteria instanceof SimpleCriteria){
            if(((ComplexCriteria)c).getPreceedingOperator(criteria) != null){
              bob.append(" " + ((ComplexCriteria)c).getPreceedingOperator(criteria) + " ");
              bob.append("(" + (conditionToAppend != null ? conditionToAppend + " AND ": ""));
              open = true;
            }
            String att = objectAttributeTodbCol.get(((SimpleCriteria) criteria).getAttribute()) != null ? objectAttributeTodbCol.get(((SimpleCriteria) criteria).getAttribute()) : ((SimpleCriteria) criteria).getAttribute();
            bob.append(att + " " + ((SimpleCriteria) criteria).getOperator() + " ?");
            if(open){
              bob.append(")");
              open = false;
            }
            params.add(((SimpleCriteria) criteria).getValue());
          }else if(criteria instanceof ComplexCriteria){
            if(((ComplexCriteria)c).getPreceedingOperator(criteria) != null){
              bob.append(" " + ((ComplexCriteria)c).getPreceedingOperator(criteria) + " ");
            }
            bob.append(" (" + (conditionToAppend != null ? conditionToAppend + " AND ": ""));
            buildComplexCriteria(objectAttributeTodbCol, (ComplexCriteria)criteria, bob, conditionToAppend, params);
            bob.append(")");
          }
        }
      }
    }
    if(!UtilMethods.isSet(conditionToAppend)&& c== null){
      bob.append(" WHERE "+ query.getBuilderType()+".inode=inode.inode");
    }
    else {
      bob.append(" AND "+ query.getBuilderType()+".inode=inode.inode");
    }
    DotConnect dc = new DotConnect();
    dc.setSQL(bob.toString().toLowerCase());
    if(params != null){
      for (Object value : params) {
        dc.addParam(value);
      }
    }
    if(query.getStart() > 0){
      dc.setStartRow(query.getStart());
    }
    if(query.getLimit() > 0){
      dc.setStartRow(query.getLimit());
    }
    String blank= "";
    List<Map<String, Object>> dbrows = dc.loadObjectResults();
    for (Map<String, Object> row : dbrows) {
      Map<String, Serializable> m = new HashMap<String, Serializable>();
       PermissionableProxy permDummy= new PermissionableProxy();
       permDummy.setPermissionByIdentifier(isPermissionsByIdentifier);
       permDummy.setInode(row.get("inode").toString());
      if(isPermissionsByIdentifier && UtilMethods.isSet(row.get("identifier"))){//DOTCMS-3739
         permDummy.setIdentifier(row.get("identifier").toString());
      }
      permDummys.add(permDummy);
      for (String colkey : row.keySet()) {
        if(colkey.startsWith("bool")|| colkey.startsWith("float")|| colkey.startsWith("integer")|| colkey.startsWith("text")|| colkey.equals("working")|| colkey.equals("deleted")){
          if(dbColToObjectAttribute.get(colkey) != null){
            if(row.get(colkey) instanceof Serializable){
              m.put(dbColToObjectAttribute.get(colkey), (Serializable) row.get(colkey));
            }else{
              m.put(dbColToObjectAttribute.get(colkey), row.get(colkey) == null ? "" : row.get(colkey).toString());
            }
          }
        }else if(colkey.startsWith("date") ){
          if(dbColToObjectAttribute.get(colkey) != null){
            if(row.get(colkey)==null){
              m.put(dbColToObjectAttribute.get(colkey), (Serializable)blank );
              }
            else{
              String date=row.get(colkey).toString();
              m.put(dbColToObjectAttribute.get(colkey), (Serializable)date);
              }
          }
        }else if(row.get(colkey) instanceof Date){
          if(row.get(colkey)==null)
            m.put(colkey, (Serializable)blank );
          else{
            String date=row.get(colkey).toString();
            m.put(colkey, (Serializable)date);
            }
        }
        else{
          m.put(colkey, (Serializable) row.get(colkey));
        }
      }
     
      try {
        permDummys=perAPI.filterCollection(permDummys, PermissionAPI.PERMISSION_READ, false, user );
      } catch (DotSecurityException e1) {

      }

      res.add(m)
View Full Code Here

  public void copyFolder(String sourcePath, String destinationPath, User user, boolean autoPublish) throws IOException, DotDataException {
    try{
      destinationPath=stripMapping(destinationPath);
      sourcePath=stripMapping(sourcePath);
      PermissionAPI perAPI = APILocator.getPermissionAPI();
      createFolder(destinationPath, user);

      Summary[] children = getChildrenData(sourcePath, user);

      for (int i = children.length - 1; i >= 0; i--) {
        // children[i] = "/" + children[i];

      if (!children[i].isFolder()) {

        createResource(destinationPath + "/" + children[i].getName(), autoPublish, user);
        setResourceContent(destinationPath + "/" + children[i].getName(), getResourceContent(sourcePath + "/" + children[i].getName(),user), null, null, user);

        // ### Copy the permission ###
        // Source
        boolean live = false;

        Identifier identifier  = APILocator.getIdentifierAPI().find(children[i].getHost(), destinationPath + "/" + children[i].getName());
        Permissionable destinationFile = null;
         if(identifier!=null && identifier.getAssetType().equals("contentlet")){
           destinationFile = APILocator.getContentletAPI().findContentletByIdentifier(identifier.getId(), live, APILocator.getLanguageAPI().getDefaultLanguage().getId(), user, false);
        }else{
          destinationFile = fileAPI.getFileByURI(destinationPath + "/" + children[i].getName(), children[i].getHost(), live, user, false);
        }

        // Delete the new permissions
        perAPI.removePermissions(destinationFile);

        // Copy the new permissions
        perAPI.copyPermissions((Permissionable)children[i].getFile(), destinationFile);

        // ### END Copy the permission ###
        // }
      } else {
        copyFolder(sourcePath + "/" + children[i].getName(), destinationPath + "/" + children[i].getName(), user, autoPublish);
      }

      }

      // ### Copy the permission ###
      // Source
      String sourceHostName = getHostname(sourcePath);
      String sourceFolderName = getPath(sourcePath);
      // String sourceFolderName = DotCMSStorage.getFolderName(sourcePath);
      Host sourceHost;

      sourceHost = hostAPI.findByName(sourceHostName, user, false);



      Folder sourceFolder = folderAPI.findFolderByPath(sourceFolderName + "/", sourceHost,user,false);
      // Destination
      String destinationHostName = getHostname(destinationPath);
      String destinationFolderName = getPath(destinationPath);
      // String destinationFolderName =
      // DotCMSStorage.getFolderName(destinationPath);
      Host destinationHost;

      destinationHost = hostAPI.findByName(destinationHostName, user, false);


      Folder destinationFolder = folderAPI.findFolderByPath(destinationFolderName + "/", destinationHost,user,false);

      // Delete the new permissions
      perAPI.removePermissions(destinationFolder);

      // Copy the new permissions
      perAPI.copyPermissions(sourceFolder, destinationFolder);
    }catch (Exception e) {
      throw new DotDataException(e.getMessage(), e);
    }
    return;
  }
View Full Code Here

    return;
  }

  public void createResource(String resourceUri, boolean publish, User user) throws IOException, DotDataException {
    try{
      PermissionAPI perAPI = APILocator.getPermissionAPI();
      Logger.debug(this.getClass(), "createResource");
      resourceUri = stripMapping(resourceUri);
      String hostName = getHostname(resourceUri);
      String path = getPath(resourceUri);
      String folderName = getFolderName(path);
      String fileName = getFileName(path);
      fileName = deleteSpecialCharacter(fileName);
      if(fileName.startsWith(".")){
        return;
      }

      Host host;

      host = hostAPI.findByName(hostName, user, false);

      Folder folder = folderAPI.findFolderByPath(folderName, host,user,false);
      boolean hasPermission = false;

      hasPermission = (!folderName.equals("/") && perAPI.doesUserHavePermission(folder, PERMISSION_CAN_ADD_CHILDREN, user, false))
                      || (folderName.equals("/") && perAPI.doesUserHavePermission(host, PERMISSION_CAN_ADD_CHILDREN, user, false));

      if (hasPermission) {
        // Check the folder filters
        if (!checkFolderFilter(folder, fileName)) {
          throw new IOException("The file doesn't comply the folder's filter");
        }

        if (host != null && InodeUtils.isSet(host.getInode())&& InodeUtils.isSet(folder.getInode())) {

          Identifier identifier = APILocator.getIdentifierAPI().find(host,path);

          File file = new File();
          file.setTitle(fileName);
          file.setFileName(fileName);
          file.setShowOnMenu(false);
          file.setModDate(new Date());
          String mimeType = fileAPI.getMimeType(fileName);
          file.setMimeType(mimeType);
          String author = user.getFullName();
          file.setAuthor(author);
          file.setModUser(author);
          file.setSortOrder(0);
          file.setShowOnMenu(false);


          if (identifier !=null &&  InodeUtils.isSet(identifier.getId()) && !identifier.getAssetType().equals("contentlet")) {
            File actualFile = fileAPI.getFileByURI(path, host, false,user,false);
            if(!UtilMethods.isSet(actualFile.getInode())){
              actualFile = (File)APILocator.getVersionableAPI().findWorkingVersion(identifier, user, false);
              WebAssetFactory.unArchiveAsset(actualFile);
            }
            if(!UtilMethods.isSet(actualFile.getInode())){
              throw new DotDataException("unable to locate file");
            }
            //            identifier = idapi.find(actualFile);
            WebAssetFactory.createAsset(file, user.getUserId(),  folder, identifier, false, false);
            if(publish && perAPI.doesUserHavePermission(file, PermissionAPI.PERMISSION_PUBLISH, user)){
              WebAssetFactory.publishAsset(file);
            }

            // ##### Copy the file data if we are creating a new
            // version #####
            String assetsPath = fileAPI.getRealAssetsRootPath();
            new java.io.File(assetsPath).mkdir();

            // creates the new file as
            // inode{1}/inode{2}/inode.file_extension
            java.io.File workingIOFile = fileAPI.getAssetIOFile(actualFile);

            //http://jira.dotmarketing.net/browse/DOTCMS-1873
            //To clear velocity cache
            DotResourceCache vc = CacheLocator.getVeloctyResourceCache();
            vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath());

            // If a new version was created, we move the current
            // data to the new version
            if (file != null && InodeUtils.isSet(file.getInode())) {
              byte[] currentData = new byte[0];
              FileInputStream is = new FileInputStream(workingIOFile);
              int size = is.available();
              currentData = new byte[size];
              is.read(currentData);
              java.io.File newVersionFile = fileAPI.getAssetIOFile(file);

              //http://jira.dotmarketing.net/browse/DOTCMS-1873
              //To clear velocity cache
              vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath());

              FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();
              ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length);
              currentDataBuffer.put(currentData);
              currentDataBuffer.position(0);
              channelTo.write(currentDataBuffer);
              channelTo.force(false);
              channelTo.close();
              file.setSize(currentData.length);
              if (UtilMethods.isImage(fileName) && workingIOFile != null) {
                try {
                  // gets image height
                  BufferedImage img = javax.imageio.ImageIO.read(workingIOFile);
                  if(img != null){
                    int height = img.getHeight();
                    file.setHeight(height);
                    // gets image width
                    int width = img.getWidth();
                    file.setWidth(width);
                  }
                } catch (Exception ioe) {
                  Logger.error(this.getClass(), ioe.getMessage(), ioe);
                }
              }
              HibernateUtil.saveOrUpdate(file);
            }
            // ##### END Copy the file data if we are creating a new
            // version #####

            // Get parents of the old version so you can update the
            // working
            // information to this new version.
            java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file);

            // update parents to new version delete old versions
            // parents if
            // not live.
            for (Tree tree : parentTrees) {
              // to keep relation types from parent only if it
              // exists
              Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode());
              if (!InodeUtils.isSet(newTree.getChild())) {
                newTree.setParent(tree.getParent());
                newTree.setChild(file.getInode());
                newTree.setRelationType(tree.getRelationType());
                newTree.setTreeOrder(0);
                TreeFactory.saveTree(newTree);
              }
            }
            APILocator.getVersionableAPI().setWorking(file);
            if(publish && perAPI.doesUserHavePermission(file, PermissionAPI.PERMISSION_PUBLISH, user))
              APILocator.getVersionableAPI().setLive(file);
            WorkingCache.removeAssetFromCache(file);
            LiveCache.removeAssetFromCache(file);
          }
View Full Code Here

  }

  public Folder createFolder(String folderUri, User user) throws IOException, DotDataException {
    Folder folder = null;
    folderUri = stripMapping(folderUri);
    PermissionAPI perAPI = APILocator.getPermissionAPI();
    Logger.debug(this.getClass(), "createFolder");
    String hostName = getHostname(folderUri);
    String path = getPath(folderUri);

    Host host;
    try {
      host = hostAPI.findByName(hostName, user, false);
    } catch (DotDataException e) {
      Logger.error(DotWebdavHelper.class, e.getMessage(), e);
      throw new IOException(e.getMessage());
    } catch (DotSecurityException e) {
      Logger.error(DotWebdavHelper.class, e.getMessage(), e);
      throw new IOException(e.getMessage());
    }

    // CheckPermission
    List<Permission> parentPermissions = new ArrayList<Permission>();
    boolean hasPermission = false;
    boolean validName = true;
    String parentPath = getFolderName(path);
    if (UtilMethods.isSet(parentPath) && !parentPath.equals("/")) {
      Folder parentFolder;
      try {
        parentFolder = folderAPI.findFolderByPath(parentPath,host,user,false);
        hasPermission = perAPI.doesUserHavePermission(parentFolder,  PERMISSION_CAN_ADD_CHILDREN, user, false);
      } catch (Exception e) {
        Logger.error(DotWebdavHelper.class,e.getMessage(),e);
        throw new IOException(e.getMessage());
      }
    } else {
      if (host != null && InodeUtils.isSet(host.getInode())) {
        java.util.List<String> reservedFolderNames = new java.util.ArrayList<String>();
        String[] reservedFolderNamesArray = Config.getStringArrayProperty("RESERVEDFOLDERNAMES");
        for (String name : reservedFolderNamesArray) {
          reservedFolderNames.add(name.toUpperCase());
        }
        validName = (!(reservedFolderNames.contains(path.substring(1).toUpperCase())));
      }
      try {
        hasPermission = perAPI.doesUserHavePermission(host, PERMISSION_CAN_ADD_CHILDREN, user, false);
      } catch (DotDataException e) {
        Logger.error(DotWebdavHelper.class,e.getMessage(),e);
        throw new IOException(e.getMessage());
      }
    }
View Full Code Here

  }

  public void move(String fromPath, String toPath, User user,boolean autoPublish)throws IOException, DotDataException {
    fromPath = stripMapping(fromPath);
    toPath = stripMapping(toPath);
    PermissionAPI perAPI = APILocator.getPermissionAPI();

    String hostName = getHostname(fromPath);
    String toParentPath = getFolderName(getPath(toPath));

    Host host;
    Folder toParentFolder;
    try {
      host = hostAPI.findByName(hostName, user, false);
        toParentFolder = folderAPI.findFolderByPath(toParentPath,host,user,false);
    } catch (DotDataException e) {
      Logger.error(DotWebdavHelper.class, e.getMessage(), e);
      throw new IOException(e.getMessage());
    } catch (DotSecurityException e) {
      Logger.error(DotWebdavHelper.class, e.getMessage(), e);
      throw new IOException(e.getMessage());
    }
    if (isResource(fromPath,user)) {
      try {
        if (!perAPI.doesUserHavePermission(toParentFolder,
            PermissionAPI.PERMISSION_READ, user, false)) {
          throw new IOException("User doesn't have permissions to move file to folder");
        }
      } catch (DotDataException e1) {
        Logger.error(DotWebdavHelper.class,e1.getMessage(),e1);
        throw new IOException(e1.getMessage());
      }
      if (toParentFolder == null || !InodeUtils.isSet(toParentFolder.getInode())) {
        throw new IOException("Cannot move a file to the root of the host.");
      }

      try{
        Identifier identifier  = APILocator.getIdentifierAPI().find(host, getPath(fromPath));

        Identifier identTo  = APILocator.getIdentifierAPI().find(host, getPath(toPath));
        boolean destinationExists=identTo!=null && InodeUtils.isSet(identTo.getId());

        if(identifier!=null && identifier.getAssetType().equals("contentlet")){
          Contentlet fileAssetCont = APILocator.getContentletAPI().findContentletByIdentifier(identifier.getId(), false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), user, false);
          if(!destinationExists) {
              if (getFolderName(fromPath).equals(getFolderName(toPath))) {
                String fileName = getFileName(toPath);
                if(fileName.contains(".")){
                  fileName = fileName.substring(0, fileName.lastIndexOf("."));
                }
                APILocator.getFileAssetAPI().renameFile(fileAssetCont, fileName, user, false);
              } else {
                APILocator.getFileAssetAPI().moveFile(fileAssetCont, toParentFolder, user, false);
              }
          }
          else {
              // if the destination exists lets just create a new version and delete the original file
              Contentlet origin = APILocator.getContentletAPI().findContentletByIdentifier(identifier.getId(), false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), user, false);
              Contentlet toContentlet = APILocator.getContentletAPI().findContentletByIdentifier(identTo.getId(), false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), user, false);
              Contentlet newversion = APILocator.getContentletAPI().checkout(toContentlet.getInode(), user, false);

              // get a copy in a tmp folder to avoid filename change
              java.io.File tmpDir=new java.io.File(APILocator.getFileAPI().getRealAssetPathTmpBinary()
                                +java.io.File.separator+UUIDGenerator.generateUuid());
              java.io.File tmp=new java.io.File(tmpDir, toContentlet.getBinary(FileAssetAPI.BINARY_FIELD).getName());
              FileUtil.copyFile(origin.getBinary(FileAssetAPI.BINARY_FIELD), tmp);

              newversion.setBinary(FileAssetAPI.BINARY_FIELD, tmp);
              newversion = APILocator.getContentletAPI().checkin(newversion, user, false);
              if(autoPublish) {
                  APILocator.getContentletAPI().publish(newversion, user, false);
              }

              APILocator.getContentletAPI().unlock(newversion, user, false);

              APILocator.getContentletAPI().delete(origin, APILocator.getUserAPI().getSystemUser(), false);
              while(APILocator.getContentletAPI().isInodeIndexed(origin.getInode(),1));
          }
        }else{
          File f = fileAPI.getFileByURI(getPath(fromPath), host, false, user, false);
          if (getFolderName(fromPath).equals(getFolderName(toPath))) {

            String fileName = getFileName(toPath);
            if(fileName.contains(".")){
              fileName = fileName.substring(0, fileName.lastIndexOf("."));
            }
            fileAPI.renameFile(f, fileName, user, false);

          } else {
            fileAPI.moveFile(f, toParentFolder, user, false);
          }
          if (autoPublish && perAPI.doesUserHavePermission(f, PermissionAPI.PERMISSION_PUBLISH, user)) {

            PublishFactory.publishAsset(f, user, false);

          }
          APILocator.getFileAPI().invalidateCache(f);
          CacheLocator.getIdentifierCache().removeFromCacheByVersionable(f);
          LiveCache.removeAssetFromCache(f);
          WorkingCache.removeAssetFromCache(f);
        }

      }catch (Exception e) {
        throw new DotDataException(e.getMessage(),e);
      }
    } else {
      if (UtilMethods.isSet(toParentPath) && !toParentPath.equals("/")) {
        try {
          if (!perAPI.doesUserHavePermission(toParentFolder,  PermissionAPI.PERMISSION_READ, user, false)) {
            throw new IOException("User doesn't have permissions to move file to folder");
          }
        } catch (DotDataException e1) {
          Logger.error(DotWebdavHelper.class,e1.getMessage(),e1);
          throw new IOException(e1.getMessage());
        }
        if (getFolderName(fromPath).equals(getFolderName(toPath))) {
          Logger.debug(this, "Calling Folderfactory to rename " + fromPath + " to " + toPath);
          try{
            Folder folder = folderAPI.findFolderByPath(getPath(toPath), host,user,false);
            removeObject(toPath, user);
            fc.removeFolder(folder,idapi.find(folder));
          }catch (Exception e) {
            Logger.debug(this, "Unable to delete toPath " + toPath);
          }
          boolean renamed = false;
          try{
            Folder folder = folderAPI.findFolderByPath(getPath(fromPath), host,user,false);
            renamed = folderAPI.renameFolder(folder, getFileName(toPath),user,false);
            fc.removeFolder(folder,idapi.find(folder));
            //folderAPI.updateMovedFolderAssets(folder);
          }catch (Exception e) {
            throw new DotDataException(e.getMessage(), e);
          }
          if(!renamed){
            Logger.error(this, "Unable to remame folder");
            throw new IOException("Unable to rename folder");
          }
        } else {
          Logger.debug(this, "Calling folder factory to move from " + fromPath + " to " + toParentPath);
          Folder fromFolder;
          try {
            fromFolder = folderAPI.findFolderByPath(getPath(fromPath), host,user,false);
          } catch (Exception e1) {
            Logger.error(DotWebdavHelper.class, e1.getMessage(), e1);
            throw new DotRuntimeException(e1.getMessage(), e1);
          }
          if(fromFolder != null){
            Logger.debug(this, "Calling folder factory to move from " + idapi.find(fromFolder).getPath() + " to " + toParentPath);
            Logger.debug(this, "the from folder inode is " + fromFolder.getInode());
          }else{
            Logger.debug(this, "The from folder is null");
          }
          try {
            folderAPI.move(fromFolder, toParentFolder,user,false);
            fc.removeFolder(fromFolder,idapi.find(fromFolder));
            fc.removeFolder(toParentFolder,idapi.find(toParentFolder));
            //folderAPI.updateMovedFolderAssets(fromFolder);
          } catch (Exception e) {
            Logger.error(DotWebdavHelper.class, e.getMessage(), e);
            throw new DotDataException(e.getMessage(), e);
          }
        }
      } else {
        try {
          if (!perAPI.doesUserHavePermission(host,PermissionAPI.PERMISSION_READ, user, false)) {
            throw new IOException("User doesn't have permissions to move file to host");
          }
        } catch (DotDataException e) {
          Logger.error(DotWebdavHelper.class,e.getMessage(),e);
          throw new IOException(e.getMessage());
View Full Code Here

TOP

Related Classes of com.dotmarketing.business.PermissionAPI

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.