コード例 #1
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> unpublishEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    Map<String, Object> callbackData = new HashMap<String, Object>(); // DOTCMS-5199
    List<String> eventUnpublishErrors = new ArrayList<String>();
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);

    try {
      contAPI.unpublish(ev, user, respectFrontendRoles);
    } catch (DotSecurityException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } catch (DotDataException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } catch (DotContentletStateException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } finally {
      if (eventUnpublishErrors.size() > 0) {
        callbackData.put("eventUnpublishErrors", eventUnpublishErrors);
      }
    }
    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }

    return callbackData;
  }
コード例 #2
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> deleteEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();
    List<String> eventDeleteErrors = new ArrayList<String>();
    Map<String, Object> callbackData = new HashMap<String, Object>();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    if (ev.isLive()) {
      try {
        contAPI.unpublish(ev, user, respectFrontendRoles);
      } catch (DotSecurityException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotDataException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotContentletStateException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    } else if (!ev.isArchived()) {
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    }

    try {
      if (ev.isArchived()) {
        contAPI.delete(ev, user, respectFrontendRoles);
      }
    } catch (Exception e) {
      eventDeleteErrors.add(e.getLocalizedMessage());
    } finally {
      if (eventDeleteErrors.size() > 0) {
        callbackData.put("eventUnpublishErrors", eventDeleteErrors);
      }
    }
    if (eventDeleteErrors.size() <= 0) {
      HibernateUtil.commitTransaction();
    }

    // At this point we already deleted the content from the index on the delete call
    /*if(!contAPI.isInodeIndexed(ev.getInode())){
    	Logger.error(this, "Timed out while waiting for index to return");
    }*/

    return callbackData;
  }
コード例 #3
0
  @SuppressWarnings("unchecked")
  public File saveFile(
      File newFile, java.io.File dataFile, Folder parentFolder, Identifier identifier)
      throws DotDataException {

    boolean localTransation = false;

    try {
      localTransation = DbConnectionFactory.getConnection().getAutoCommit();
      if (localTransation) {
        HibernateUtil.startTransaction();
      }
      // old working file
      File oldFile = null;
      // if new identifier
      if (identifier == null || !InodeUtils.isSet(identifier.getInode())) {
        identifier = APILocator.getIdentifierAPI().createNew(newFile, parentFolder);
        newFile.setIdentifier(identifier.getInode());
        HibernateUtil.save(newFile);
        APILocator.getVersionableAPI().setWorking(newFile);
        saveFileData(newFile, null, dataFile);
      } else {
        APILocator.getVersionableAPI().removeLive(identifier.getId());
      }
      if (UtilMethods.isSet(dataFile)) {
        HibernateUtil.save(newFile);
        saveFileData(newFile, null, dataFile);
      }
      if (oldFile != null && InodeUtils.isSet(oldFile.getInode())) {
        APILocator.getFileAPI().invalidateCache(oldFile);
        fileCache.remove(oldFile);
        WorkingCache.removeAssetFromCache(oldFile);
      }
      LiveCache.removeAssetFromCache(newFile);
      if (newFile.isLive()) {
        LiveCache.addToLiveAssetToCache(newFile);
      }
      WorkingCache.addToWorkingAssetToCache(newFile);

      if (localTransation) {
        HibernateUtil.commitTransaction();
      }
    } catch (Exception e) {
      if (localTransation) {
        HibernateUtil.rollbackTransaction();
      }
      throw new DotDataException(e.getMessage(), e);
    }
    return newFile;
  }
コード例 #4
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public void unarchiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {

      if (UtilMethods.isSet(ev.getDisconnectedFrom())) {
        Event baseEvent = null;
        try {
          baseEvent = eventAPI.find(ev.getDisconnectedFrom(), false, user, respectFrontendRoles);
        } catch (Exception e) {
          Logger.error(this, "Base event not found");
        }
        if (baseEvent != null) {
          try {
            Date originalStartDate = ev.getOriginalStartDate();
            baseEvent.addDateToIgnore(originalStartDate);
            APILocator.getContentletAPI()
                .checkin(
                    baseEvent,
                    categoryAPI.getParents(baseEvent, user, true),
                    perAPI.getPermissions(baseEvent),
                    user,
                    false);
          } catch (Exception e) {
            Logger.error(this, "Could not delete event from recurrence");
          }
        }
      }
      contAPI.unarchive(ev, user, respectFrontendRoles);

    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
コード例 #5
0
  /** Thread main method to start the calendar reminder process */
  @SuppressWarnings("unchecked")
  public void run() {
    Logger.debug(this, "Running Calendar Reminder Job");

    try {
      HibernateUtil.startTransaction();
      CalendarReminderAPI CRAI = APILocator.getCalendarReminderAPI();
      Date now = new Date();
      CRAI.sendCalendarRemainder(now);
      Logger.debug(this, "The Calendar Reminder Job End successfully");
    } catch (Exception e) {
      Logger.warn(this, e.toString());
    } finally {
      try {
        HibernateUtil.commitTransaction();
      } catch (Exception e) {
        Logger.warn(this, e.toString());
      }
    }
  }
コード例 #6
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public void archiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {
      contAPI.archive(ev, user, respectFrontendRoles);
    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
コード例 #7
0
  public static int deleteOldAssetVersions(Date assetsOlderThan) {
    int counter = 0;
    int auxCount = 0;

    /*
     * Run the drop tasks interatively, moving forward in time
     * DROP_OLD_ASSET_ITERATE_BY_SECONDS controls how many seconds to
     * move forward in time for each iteration - default is to iterate by 30 days
     */
    Calendar runDate = Calendar.getInstance();
    runDate.setTime(assetsOlderThan);
    runDate.add(Calendar.YEAR, -2);

    try {
      DotConnect dc = new DotConnect();
      String minIdateSQL = "select idate from inode order by idate";

      dc.setSQL(minIdateSQL);
      dc.setMaxRows(1);
      List<Map<String, Object>> map = dc.loadObjectResults();
      Date d = (Date) map.get(0).get("idate");
      if (d != null) runDate.setTime(d);
    } catch (Exception e) {
      Logger.info(CMSMaintenanceFactory.class, "Can't get start date");
    }

    while (runDate.getTime().before(assetsOlderThan) || runDate.getTime().equals(assetsOlderThan)) {
      try {
        HibernateUtil.startTransaction();
        Logger.info(
            CMSMaintenanceFactory.class,
            "Starting deleteOldAssetVersions for date: "
                + UtilMethods.dateToHTMLDate(runDate.getTime(), "yyyy-MM-dd"));

        ContentletAPI conAPI = APILocator.getContentletAPI();

        Logger.info(CMSMaintenanceFactory.class, "Removing Contentlets");
        auxCount = conAPI.deleteOldContent(runDate.getTime());
        counter = auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Contentlets");

        Logger.info(CMSMaintenanceFactory.class, "Removing HTML Pages");
        auxCount = APILocator.getHTMLPageAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " HTML Pages");

        Logger.info(CMSMaintenanceFactory.class, "Removing Containers");
        auxCount = APILocator.getContainerAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Containers");

        Logger.info(CMSMaintenanceFactory.class, "Removing Templates");
        auxCount = APILocator.getTemplateAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Templates");

        Logger.info(CMSMaintenanceFactory.class, "Removing Links");
        auxCount = APILocator.getMenuLinkAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Links");

        Logger.info(CMSMaintenanceFactory.class, "Removing File Assets");

        auxCount = APILocator.getFileAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " File Assets");

        Logger.info(
            CMSMaintenanceFactory.class,
            "Finished removing old asset versions, removed " + counter + " assets");

        // This is the last run, break
        if (runDate.getTime().equals(assetsOlderThan)) {
          break;
        }
        runDate.add(
            Calendar.SECOND,
            Config.getIntProperty("DROP_OLD_ASSET_ITERATE_BY_SECONDS", 60 * 60 * 24 * 30));

        // we should never go past the date the user entered
        if (runDate.getTime().after(assetsOlderThan)) {
          runDate.setTime(assetsOlderThan);
        }

      } catch (Exception ex) {
        try {
          HibernateUtil.rollbackTransaction();
        } catch (DotHibernateException e) {
          Logger.error(CMSMaintenanceFactory.class, e.getMessage());
        }
        Logger.debug(
            CMSMaintenanceFactory.class, "There was a problem deleting old asset versions", ex);
        Logger.warn(
            CMSMaintenanceFactory.class, "There  was a problem deleting old asset versions", ex);
        Logger.error(ViewCMSMaintenanceAction.class, ex.toString(), ex);
        if (counter > 0) {
          CacheLocator.getCacheAdministrator().flushAll();
        }
        return -1;
      } finally {
        try {
          HibernateUtil.commitTransaction();
        } catch (DotHibernateException e) {
          Logger.error(CMSMaintenanceFactory.class, e.getMessage());
          try {
            HibernateUtil.rollbackTransaction();
          } catch (DotHibernateException ex) {
            Logger.error(CMSMaintenanceFactory.class, e.getMessage());
          }
          Logger.debug(
              CMSMaintenanceFactory.class, "There was a problem deleting old asset versions", e);
          Logger.warn(
              CMSMaintenanceFactory.class, "There  was a problem deleting old asset versions", e);
          Logger.error(ViewCMSMaintenanceAction.class, e.toString(), e);
          if (counter > 0) {
            CacheLocator.getCacheAdministrator().flushAll();
          }
          return -1;
        }
      }
    }
    if (counter > 0) {
      CacheLocator.getCacheAdministrator().flushAll();
    }
    return counter;
  }
コード例 #8
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL)
        && LicenseUtil.getLevel() < 299) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.ORACLE)
        && LicenseUtil.getLevel() < 399) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (!LicenseUtil.isASAllowed()) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    Long profileTime = null;
    if (Config.getBooleanProperty("VELOCITY_PROFILING", false)) {
      profileTime = Calendar.getInstance().getTimeInMillis();
    }
    try {

      // Check if the uri is a physical file. Fix for the cases when the
      // site configure VELOCITY_PAGE_EXTENSION as htm, html or any known
      // extension.
      // Example:
      // /html/js/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm
      String uri = request.getRequestURI();
      uri = URLDecoder.decode(uri, "UTF-8");
      File file = new File(Config.CONTEXT.getRealPath(uri));
      if (file.exists()) {
        FileInputStream fileIS = new FileInputStream(file);
        ServletOutputStream servletOS = response.getOutputStream();
        int b;
        for (; -1 < (b = fileIS.read()); ) {
          servletOS.write(b);
        }
        fileIS.close();
        servletOS.flush();
        servletOS.close();
        return;
      }

      // If we are at a directory, e.g. /home
      // we need to redirect to /home/
      String forwardFor = (String) request.getRequestURL().toString();
      if (request.getAttribute(Globals.MAPPING_KEY) == null
          && forwardFor != null
          && !forwardFor.endsWith("/")
          && !forwardFor.endsWith("." + Config.getStringProperty("VELOCITY_PAGE_EXTENSION"))) {
        // The query string parameters should be preserved as well
        String queryString = request.getQueryString();
        response.sendRedirect(
            forwardFor + "/" + (UtilMethods.isSet(queryString) ? "?" + queryString : ""));
        return;
      }

      HttpSession session = request.getSession(false);
      boolean ADMIN_MODE =
          session != null
              && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null);
      boolean PREVIEW_MODE =
          ADMIN_MODE
              && (session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null);
      boolean EDIT_MODE =
          ADMIN_MODE
              && (session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null);

      String value = request.getHeader("X-Requested-With");
      if ((value != null) && value.equals("XMLHttpRequest") && EDIT_MODE && ADMIN_MODE) {
        ADMIN_MODE = false;
      }

      // ### VALIDATE ARCHIVE ###
      if ((EDIT_MODE || PREVIEW_MODE) && isArchive(request)) {
        PREVIEW_MODE = true;
        EDIT_MODE = false;
        request.setAttribute("archive", true);
      }
      // ### END VALIDATE ARCHIVE ###

      LanguageWebAPI langWebAPI = WebAPILocator.getLanguageWebAPI();
      langWebAPI.checkSessionLocale(request);

      if (PREVIEW_MODE && ADMIN_MODE) {
        // preview mode has the left hand menu and edit buttons on the
        // working page

        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON PREVIEW MODE!!!");

        doPreviewMode(request, response);
      } else if (EDIT_MODE && ADMIN_MODE) {
        // edit mode has the left hand menu and edit buttons on the
        // working page

        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON EDIT MODE!!!");

        doEditMode(request, response);
      } else if (ADMIN_MODE) {
        // admin mode has the left hand menu and shows the live page in
        // the frame
        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON ADMIN MODE!!!");

        doAdminMode(request, response);
      } else {
        // live mode has no frame and shows the live page
        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON LIVE MODE!!!");

        doLiveMode(request, response);
      }

    } catch (ResourceNotFoundException rnfe) {

      // response.sendError(404);
      request.setAttribute(Constants.SERVE_URL, request.getRequestURI());
      request.getRequestDispatcher("/localResourceServlet").forward(request, response);

    } catch (ParseErrorException pee) {
      Logger.error(this, "Template Parse Exception : " + pee.toString(), pee);
      try {
        response.sendError(500, "Template Parse Exception");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println("Template Parse Exception");
        out.println("On template:" + request.getRequestURI() + request.getQueryString());
      }

    } catch (MethodInvocationException mie) {
      Logger.error(this, "MethodInvocationException" + mie.toString(), mie);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println(
            "MethodInvocationException Error on template:"
                + request.getRequestURI()
                + request.getQueryString());
      }
    } catch (Exception e) {
      Logger.error(this, e.toString(), e);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println("Error on template:" + request.getRequestURI() + request.getQueryString());
      }
    } finally {
      // catchall
      // added finally because of
      // http://jira.dotmarketing.net/browse/DOTCMS-1334
      try {
        HibernateUtil.commitTransaction();
      } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
      }
      DbConnectionFactory.closeConnection();
    }
    if (profileTime != null) {
      profileTime = Calendar.getInstance().getTimeInMillis() - profileTime;
      VelocityProfiler.log(
          VelocityServlet.class,
          "VelocityPage time: " + request.getRequestURL() + " " + profileTime + " millis");
    }
  }
コード例 #9
0
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      ActionRequest req,
      ActionResponse res)
      throws Exception {

    String cmd = req.getParameter(Constants.CMD);
    String referer = req.getParameter("referer");

    if ((referer != null) && (referer.length() != 0)) {
      referer = URLDecoder.decode(referer, "UTF-8");
    }

    // Load the structure in the request
    try {
      Logger.debug(this, "Calling Retrieve method");
      _loadStructure(form, req, res);
    } catch (Exception ae) {
      _handleException(ae, req);
      return;
    }

    HibernateUtil.startTransaction();
    boolean returnToList = false;
    /*
     * If we are updating the workflow message, copy the information from
     * the struts bean to the hbm inode and run the update action and return
     * to the list
     */
    if ((cmd != null) && cmd.equals(Constants.ADD)) {
      try {
        Logger.debug(this, "Calling Add/Edit Method");
        if (Validator.validate(req, form, mapping)) {

          if (UtilMethods.isSet(((StructureForm) form).getInode())) {
            returnToList = true;
          }

          _saveStructure(form, req, res);
        }

      } catch (Exception ae) {
        _handleException(ae, req);
        return;
      }

    }
    /*
     * If we are deleteing the structure, run the delete action and return
     * to the list
     *
     */
    else if ((cmd != null) && cmd.equals(Constants.DELETE)) {
      try {
        Logger.debug(this, "Calling Delete Method");
        _deleteStructure(form, req, res);
      } catch (Exception ae) {
        _handleException(ae, req);
        return;
      }
      _sendToReferral(req, res, referer);
      return;
    } else if ((cmd != null) && cmd.equals(WebKeys.Structure.SET_DEFAULT)) {
      try {
        _defaultStructure(form, req, res);
      } catch (Exception ae) {
        _handleException(ae, req);
        return;
      }
      _sendToReferral(req, res, referer);
      return;
    } else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.RESET)) {
      try {
        _resetIntervals(form, req, res);
      } catch (Exception ae) {
        _handleException(ae, req);
        return;
      }
      _sendToReferral(req, res, referer);
      return;
    }

    HibernateUtil.commitTransaction();
    _loadForm(form, req, res);
    if (returnToList) {
      if (!UtilMethods.isSet(referer)) {
        java.util.Map<String, String[]> params = new java.util.HashMap<String, String[]>();

        if (((StructureForm) form).getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
          params.put("struts_action", new String[] {"/ext/formhandler/view_form"});
        } else {
          params.put("struts_action", new String[] {"/ext/structure/view_structure"});
        }

        referer =
            com.dotmarketing.util.PortletURLUtil.getActionURL(
                req, WindowState.MAXIMIZED.toString(), params);
      }
      _sendToReferral(req, res, referer);
    } else {
      setForward(req, "portlet.ext.structure.edit_structure");
    }
  }
コード例 #10
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> saveEvent(List<String> formData, boolean isAutoSave, boolean isCheckin)
      throws LanguageException, PortalException, SystemException, DotDataException,
          DotSecurityException, java.text.ParseException {

    HibernateUtil.startTransaction();
    ContentletWebAPI contentletWebAPI = WebAPILocator.getContentletWebAPI();
    int tempCount =
        0; // To store multiple values opposite to a name. Ex: selected permissions & categories
    String newInode = "";

    String referer = "";
    String language = "";
    String strutsAction = "";
    String recurrenceDaysOfWeek = "";

    Map<String, Object> contentletFormData = new HashMap<String, Object>();
    Map<String, Object> callbackData = new HashMap<String, Object>();
    List<String> saveContentErrors = new ArrayList<String>();

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
    User user = com.liferay.portal.util.PortalUtil.getUser((HttpServletRequest) req);
    List<Field> fields =
        com.dotmarketing.cache.FieldsCache.getFieldsByStructureInode(
            eventAPI.getEventStructure().getInode());
    String titleField = "";
    String urlTitleField = "";
    String urlTitleFieldValue = "";
    String titleFieldValue = "";

    for (Field field : fields) {
      if (field.getVelocityVarName().equals("urlTitle")) {
        urlTitleField = field.getFieldContentlet();
      }
      if (field.getVelocityVarName().equals("title")) {
        titleField = field.getFieldContentlet();
      }
      if (UtilMethods.isSet(titleField) && UtilMethods.isSet(urlTitleField)) {
        break;
      }
    }

    // get the struts_action from the form data
    for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) {
      String element = iterator.next();
      if (element != null) {
        String elementName =
            element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR));

        if (elementName.startsWith("_EXT") && elementName.endsWith("cmd")) {
          strutsAction = elementName.substring(0, elementName.indexOf("cmd"));
          break;
        }
      }
    }

    // Storing form data into map.
    for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) {
      String element = iterator.next();

      if (!com.dotmarketing.util.UtilMethods.isSet(element)) continue;

      String elementName =
          element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR));
      Object elementValue =
          element.substring(
              element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR)
                  + WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR.length());

      if (element.startsWith(strutsAction))
        elementName =
            elementName.substring(elementName.indexOf(strutsAction) + strutsAction.length());

      // Placed increments as Map holds unique keys.
      if (elementName.equals("read")
          || elementName.equals("write")
          || elementName.equals("publish")) {

        tempCount++;
        elementName = "selected_permission_" + tempCount + elementName;
      }

      if (elementName.equals(titleField)) {
        titleFieldValue = (String) elementValue;
      }

      if (elementName.equals(urlTitleField)) {
        urlTitleFieldValue = (String) elementValue;
      }

      if (elementName.equals("categories")) {
        tempCount++;
        elementName = elementName + tempCount + "_";
      }
      // http://jira.dotmarketing.net/browse/DOTCMS-3232
      if (elementName.equalsIgnoreCase("hostId")) {
        callbackData.put("hostOrFolder", true);
      }
      if (elementName.startsWith("binary")) {
        String binaryFileValue = (String) elementValue;
        if (UtilMethods.isSet(binaryFileValue) && !binaryFileValue.equals("---removed---")) {
          binaryFileValue = ContentletUtil.sanitizeFileName(binaryFileValue);

          File binaryFile =
              new File(
                  APILocator.getFileAPI().getRealAssetPathTmpBinary()
                      + File.separator
                      + user.getUserId()
                      + File.separator
                      + elementName
                      + File.separator
                      + binaryFileValue);
          if (binaryFile.exists()) binaryFile.delete();
          elementValue = binaryFile;
        } else {
          elementValue = null;
        }
      }

      if (!UtilMethods.isSet(elementName)) continue;

      if (elementValue == null) elementValue = "";

      if (elementName.equals("referer")) referer = (String) elementValue;

      if (elementName.equals("languageId")) language = (String) elementValue;

      if (elementName.equals("recurrenceDaysOfWeek")) {
        recurrenceDaysOfWeek = recurrenceDaysOfWeek + elementValue + ",";
      }
      contentletFormData.put(elementName, elementValue);
    }

    contentletFormData.put("recurrenceDaysOfWeek", recurrenceDaysOfWeek);

    if (!UtilMethods.isSet(urlTitleFieldValue) && UtilMethods.isSet(titleFieldValue)) {

      urlTitleFieldValue = titleFieldValue.toLowerCase();
      urlTitleFieldValue = urlTitleFieldValue.replace("/^\\s+|\\s+$/g", "");
      urlTitleFieldValue = urlTitleFieldValue.replace("/[^a-zA-Z 0-9]+/g", " ");
      urlTitleFieldValue = urlTitleFieldValue.replace("/\\s/g", "-");
      while (urlTitleFieldValue.indexOf("--") > -1) {
        urlTitleFieldValue = urlTitleFieldValue.replace("--", "-");
      }
      contentletFormData.put(urlTitleField, urlTitleFieldValue);
    }

    String d1 = (String) contentletFormData.get("date1");
    String d2 = (String) contentletFormData.get("date2");
    String d3 = (String) contentletFormData.get("recurrenceEnds");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
    Date eventStartDate = null;
    Date eventEndDate = null;
    Date recurrenceEndDate = null;
    try {
      eventStartDate = df.parse(d1);
      eventEndDate = df.parse(d2);
      if (UtilMethods.isSet(d3)) {
        recurrenceEndDate = df2.parse(d3);
      }
    } catch (java.text.ParseException e1) {

    }
    Boolean cont = true;

    if (eventEndDate.before(eventStartDate)) {
      String errorString = LanguageUtil.get(user, "message.event.endate.before.stardate");
      saveContentErrors.add(errorString);
    }

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) {
        if (recurrenceEndDate != null && recurrenceEndDate.before(eventStartDate)) {
          String errorString =
              LanguageUtil.get(user, "message.event.recurrence.endate.before.stardate");
          saveContentErrors.add(errorString);
        }
      }
    }

    Calendar start = Calendar.getInstance();
    start.setTime(eventStartDate);
    Calendar end = Calendar.getInstance();
    end.setTime(eventEndDate);

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (end.after(start)
          && (end.get(Calendar.DAY_OF_MONTH) > start.get(Calendar.DAY_OF_MONTH)
              || end.get(Calendar.MONTH) > start.get(Calendar.MONTH)
              || end.get(Calendar.YEAR) > start.get(Calendar.YEAR))) {
        contentletFormData.put("recurrenceOccurs", "never");
      }
    }

    if (Boolean.parseBoolean(contentletFormData.get("recurrenceChanged").toString())) {
      if (!UtilMethods.isSet(contentletFormData.get("recurrenceInterval"))) {
        String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval");
        saveContentErrors.add(errorString);
      } else {
        try {
          Long.valueOf((String) contentletFormData.get("recurrenceInterval"));
        } catch (NumberFormatException nfe) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval");
          saveContentErrors.add(errorString);
        }
      }

      if (contentletFormData.get("recurrenceOccurs").toString().equals("monthly")) {
        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && !UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) {
          String errorString =
              LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
          saveContentErrors.add(errorString);
        }

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) {
          try {
            Long.valueOf((String) contentletFormData.get("recurrenceDayOfMonth"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
            saveContentErrors.add(errorString);
          }
        } else {
          contentletFormData.put("recurrenceDayOfMonth", "0");
        }
      }

      if (contentletFormData.get("recurrenceOccurs").toString().equals("annually")) {

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && !UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY"))
            && !UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.date");
          saveContentErrors.add(errorString);
        }

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY"))
            && UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) {
          try {
            Long.valueOf((String) contentletFormData.get("specificDayOfMonthRecY"));
            contentletFormData.put(
                "recurrenceDayOfMonth", (String) contentletFormData.get("specificDayOfMonthRecY"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
            saveContentErrors.add(errorString);
          }
          try {
            Long.valueOf((String) contentletFormData.get("specificMonthOfYearRecY"));
            contentletFormData.put(
                "recurrenceMonthOfYear",
                (String) contentletFormData.get("specificMonthOfYearRecY"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.monthofyear");
            saveContentErrors.add(errorString);
          }
        } else {
          contentletFormData.put("recurrenceDayOfMonth", "0");
        }
      }
    }

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || (contentletFormData.get("noEndDate") != null
              && !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString()))) {
        if (!UtilMethods.isSet((String) contentletFormData.get("recurrenceEnds"))) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate");
          saveContentErrors.add(errorString);
        } else {
          try {
            eventRecurrenceEndDateF.parse((String) contentletFormData.get("recurrenceEnds"));
          } catch (Exception e) {
            String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate");
            saveContentErrors.add(errorString);
          }
        }
      }
    }

    // http://jira.dotmarketing.net/browse/DOTCMS-6327
    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) {
        Integer interval =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceInterval"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceInterval"))
                : null;
        Integer recurrenceWeekOfMonth =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceWeekOfMonth"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceWeekOfMonth"))
                : null;
        Integer recurrenceDayOfWeek =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfWeek"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfWeek"))
                : null;
        Integer recurrenceMonthOfYear =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceMonthOfYear"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceMonthOfYear"))
                : null;
        Integer recurrenceDayOfMonth =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfMonth"))
                : null;
        Occurrency occurency =
            Occurrency.findOcurrency((String) contentletFormData.get("recurrenceOccurs"));

        if (occurency != null) {
          Calendar firstOccurence =
              RecurrenceUtil.calculateFirstOccurence(
                  eventStartDate,
                  interval,
                  occurency,
                  recurrenceDaysOfWeek,
                  recurrenceWeekOfMonth,
                  recurrenceDayOfWeek,
                  recurrenceMonthOfYear,
                  recurrenceDayOfMonth);
          if (recurrenceEndDate.before(firstOccurence.getTime())) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.before.occurence");
            saveContentErrors.add(errorString);
          }
        }
      }
    }

    try {
      if (cont && (saveContentErrors == null || saveContentErrors.isEmpty())) {
        newInode = contentletWebAPI.saveContent(contentletFormData, isAutoSave, isCheckin, user);
      }
    } catch (DotContentletValidationException ve) {

      if (ve.hasRequiredErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_REQUIRED);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.required");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasLengthErrors()) {
        List<Field> reqs =
            ve.getNotValidFields()
                .get(DotContentletValidationException.VALIDATION_FAILED_MAXLENGTH);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.maxlength");
          errorString = errorString.replace("{0}", field.getFieldName());
          errorString = errorString.replace("{1}", "225");
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasPatternErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_PATTERN);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.format");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasRelationshipErrors()) {
        StringBuffer sb = new StringBuffer("<br>");
        Map<String, Map<Relationship, List<Contentlet>>> notValidRelationships =
            ve.getNotValidRelationship();
        Set<String> auxKeys = notValidRelationships.keySet();
        for (String key : auxKeys) {
          String errorMessage = "";
          if (key.equals(DotContentletValidationException.VALIDATION_FAILED_REQUIRED_REL)) {
            errorMessage = "<b>Required Relationship</b>";
          } else if (key.equals(
              DotContentletValidationException.VALIDATION_FAILED_INVALID_REL_CONTENT)) {
            errorMessage = "<b>Invalid Relationship-Contentlet</b>";
          } else if (key.equals(DotContentletValidationException.VALIDATION_FAILED_BAD_REL)) {
            errorMessage = "<b>Bad Relationship</b>";
          }

          sb.append(errorMessage + ":<br>");
          Map<Relationship, List<Contentlet>> relationshipContentlets =
              notValidRelationships.get(key);

          for (Entry<Relationship, List<Contentlet>> relationship :
              relationshipContentlets.entrySet()) {
            sb.append(relationship.getKey().getRelationTypeValue() + ", ");
          }
          sb.append("<br>");
        }
        sb.append("<br>");

        // need to update message to support multiple relationship validation errors
        String errorString = LanguageUtil.get(user, "message.relationship.required_ext");
        errorString = errorString.replace("{0}", sb.toString());
        saveContentErrors.add(errorString);
      }

      if (ve.hasUniqueErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_UNIQUE);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.unique");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.getMessage()
          .contains(
              "The content form submission data id different from the content which is trying to be edited")) {
        String errorString = LanguageUtil.get(user, "message.contentlet.invalid.form");
        saveContentErrors.add(errorString);
      }

    } catch (DotSecurityException dse) {
      String errorString = LanguageUtil.get(user, "message.insufficient.permissions.to.save");
      saveContentErrors.add(errorString);

    } catch (Exception e) {
      if (e.getMessage().equals(Constants.COMMON_ERROR)) {
        String errorString = LanguageUtil.get(user, "message.contentlet.save.error");
        saveContentErrors.add(errorString);
        SessionMessages.clear(req.getSession());
      } else {
        saveContentErrors.add(e.getLocalizedMessage());
      }

    } finally {
      if (!isAutoSave && (saveContentErrors != null && saveContentErrors.size() > 0)) {
        callbackData.put("saveContentErrors", saveContentErrors);
        SessionMessages.clear(req.getSession());
      }
    }

    if (InodeUtils.isSet(newInode)) callbackData.put("contentletInode", newInode);

    if (!isAutoSave && (saveContentErrors == null || saveContentErrors.size() == 0)) {

      Logger.debug(this, "AFTER PUBLISH LANGUAGE=" + language);

      if (UtilMethods.isSet(language) && referer.indexOf("language") > -1) {
        Logger.debug(this, "Replacing referer language=" + referer);
        referer =
            referer.replaceAll(
                "language=([0-9])*",
                com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE + "=" + language);
        Logger.debug(this, "Referer after being replaced=" + referer);
      }
    }

    boolean savingRecurrence = false;
    callbackData.put("referer", referer);
    HibernateUtil.commitTransaction();
    if (UtilMethods.isSet(newInode) && !savingRecurrence) {
      if (!contAPI.isInodeIndexed(newInode)) {
        Logger.error(this, "Timed out while waiting for index to return");
      }
    }
    return callbackData;
  }
コード例 #11
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> disconnectEvent(String inode, String startDateStr, String endDateStr)
      throws DotRuntimeException, PortalException, SystemException, DotDataException,
          DotSecurityException, java.text.ParseException {

    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Map<String, Object> eventMap = new HashMap<String, Object>();
    List<String> disconnectEventErrors = new ArrayList<String>();

    String inodeStr = (InodeUtils.isSet(inode) ? inode : "");
    Contentlet contentlet = new Contentlet();
    if (InodeUtils.isSet(inodeStr)) {
      contentlet = contAPI.find(inodeStr, user, false);
    }
    if (InodeUtils.isSet(contentlet.getInode())) {
      Event ev = null;
      try {
        ev = eventAPI.find(contentlet.getIdentifier(), false, user, respectFrontendRoles);
      } catch (Exception e) {
        disconnectEventErrors.add(e.getLocalizedMessage());
      } finally {
        if (disconnectEventErrors.size() > 0) {
          eventMap.put("disconnectEventErrors", disconnectEventErrors);
        }
      }

      if (ev != null) {
        Date startDate = null;
        Date endDate = null;

        try {
          if (UtilMethods.isSet(startDateStr)) {
            String date = dateFormat.format(dateFormat2.parse(startDateStr));
            startDate = dateFormat.parse(date);
          }
          if (UtilMethods.isSet(endDateStr)) {
            String date = dateFormat.format(dateFormat2.parse(endDateStr));
            endDate = dateFormat.parse(date);
          }

        } catch (java.text.ParseException pe) {
          disconnectEventErrors.add(pe.getLocalizedMessage());
        } finally {
          if (disconnectEventErrors.size() > 0) {
            eventMap.put("disconnectEventErrors", disconnectEventErrors);
          }
        }

        if (startDate != null && endDate != null) {
          Calendar originalStartDate = Calendar.getInstance();
          Calendar originalEndDate = Calendar.getInstance();
          Calendar newStartDate = Calendar.getInstance();
          Calendar newEndDate = Calendar.getInstance();
          originalStartDate.setTime(ev.getStartDate());
          originalEndDate.setTime(ev.getEndDate());
          newStartDate.setTime(startDate);
          newEndDate.setTime(endDate);

          originalStartDate.set(Calendar.YEAR, newStartDate.get(Calendar.YEAR));
          originalStartDate.set(Calendar.MONTH, newStartDate.get(Calendar.MONTH));
          originalStartDate.set(Calendar.DAY_OF_MONTH, newStartDate.get(Calendar.DAY_OF_MONTH));

          originalEndDate.set(Calendar.YEAR, newEndDate.get(Calendar.YEAR));
          originalEndDate.set(Calendar.MONTH, newEndDate.get(Calendar.MONTH));
          originalEndDate.set(Calendar.DAY_OF_MONTH, newEndDate.get(Calendar.DAY_OF_MONTH));

          Event newEvent = null;

          try {
            boolean autoCom = false;
            try {
              autoCom = DbConnectionFactory.getConnection().getAutoCommit();
            } catch (Exception e) {
              throw new DotDataException(e.getMessage());
            }
            if (autoCom) {
              HibernateUtil.startTransaction();
            }
            newEvent =
                eventAPI.disconnectEvent(
                    ev, user, originalStartDate.getTime(), originalEndDate.getTime());
            eventMap = newEvent.getMap();
            // Loading categories
            List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>();
            List<Category> eventCategories =
                categoryAPI.getParents(newEvent, user, respectFrontendRoles);
            for (Category cat : eventCategories) {
              categoryMaps.add(cat.getMap());
            }
            eventMap.put("categories", categoryMaps);
            eventMap.put("rating", RatingAPI.getAverageRating(newEvent.getIdentifier()));
            eventMap.put("votes", RatingAPI.getRatingVotesNumber(newEvent.getIdentifier()));
            eventMap.put(
                "hasReadPermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
            eventMap.put(
                "hasWritePermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
            eventMap.put(
                "hasPublishPermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
            eventMap.put(
                "readPermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
            eventMap.put(
                "writePermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
            eventMap.put(
                "publishPermission",
                perAPI.doesUserHavePermission(
                    newEvent, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
            eventMap.put("isDisconnected", UtilMethods.isSet(newEvent.getDisconnectedFrom()));
            CommentsWebAPI cAPI = new CommentsWebAPI();
            cAPI.setUser(user);
            cAPI.setRespectFrontendRoles(respectFrontendRoles);
            eventMap.put("commentsCount", cAPI.getCommentsCount(newEvent.getInode()));
            HibernateUtil.commitTransaction();
          } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
            disconnectEventErrors.add(e.getLocalizedMessage());
          } finally {
            if (disconnectEventErrors.size() > 0) {
              eventMap.put("disconnectEventErrors", disconnectEventErrors);
            }
          }
        }
      }
    }

    return eventMap;
  }
コード例 #12
0
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      ActionRequest req,
      ActionResponse res)
      throws Exception {

    String cmd = req.getParameter("cmd");
    String subcmd = ParamUtil.getString(req, "subcmd");
    String referer =
        (req.getParameter("referer") != null)
            ? URLDecoder.decode(req.getParameter("referer"), "UTF-8")
            : "/c";

    Logger.debug(DirectorAction.class, "DirectorAction :: referer=" + referer);

    // wraps request to get session object
    ActionRequestImpl reqImpl = (ActionRequestImpl) req;
    HttpServletRequest httpReq = reqImpl.getHttpServletRequest();
    // gets the session object for the messages
    HttpSession session = httpReq.getSession();

    Logger.debug(DirectorAction.class, "I'm inside the Director cmd = " + cmd);
    Logger.debug(DirectorAction.class, "I'm inside the Director subcmd = " + subcmd);
    Logger.debug(DirectorAction.class, "I'm inside the Director referer = " + referer);

    // get the user
    User user = _getUser(req);

    // to order menu items
    if (cmd != null && cmd.equals("orderMenu")) {

      Logger.debug(DirectorAction.class, "Director :: orderMenu");

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/folders/order_menu"});
      params.put("path", new String[] {req.getParameter("path")});
      params.put("pagePath", new String[] {req.getParameter("pagePath")});
      if (req.getParameter("openAll") != null) {
        params.put("openAll", new String[] {req.getParameter("openAll")});
      }
      params.put("hostId", new String[] {req.getParameter("hostId")});
      params.put("referer", new String[] {referer});

      params.put("startLevel", new String[] {req.getParameter("startLevel")});
      params.put("depth", new String[] {req.getParameter("depth")});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);

      return;
    }
    if (cmd != null && cmd.equals("orderContentlets")) {

      Logger.debug(DirectorAction.class, "Director :: orderContentlet");

      Container container =
          (Container) InodeFactory.getInode(req.getParameter("containerId"), Container.class);
      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("pageId"), HTMLPage.class);
      boolean hasReadPermissionOnContainer =
          perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false);
      boolean hasWritePermissionOnPage =
          perAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user, false);

      if (!hasReadPermissionOnContainer || !hasWritePermissionOnPage) {
        throw new DotSecurityException(
            "User has no permission to reorder content on container = "
                + req.getParameter("container")
                + " on page = "
                + req.getParameter("htmlPage"));
      }

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/contentlet/order_contentlets"});
      params.put("containerId", new String[] {req.getParameter("containerId")});
      params.put("pageId", new String[] {req.getParameter("pageId")});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);

      return;
    }

    if (cmd != null && cmd.equals("newHTMLPage")) {

      Logger.debug(DirectorAction.class, "Director :: editHTMLPage");

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/htmlpages/edit_htmlpage"});
      params.put("cmd", new String[] {"edit"});
      params.put("inode", new String[] {"0"});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("editHTMLPage")) {

      Logger.debug(DirectorAction.class, "Director :: editHTMLPage");

      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

      Identifier identifier = APILocator.getIdentifierAPI().find(htmlPage);
      // gets the current working asset
      WebAsset workingHTMLPage =
          (WebAsset)
              APILocator.getVersionableAPI()
                  .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);

      if ("unlockHTMLPage".equals(subcmd)) {
        WebAssetFactory.unLockAsset(workingHTMLPage);
      }

      if (workingHTMLPage.isLocked() && !workingHTMLPage.getModUser().equals(user.getUserId())) {
        req.setAttribute(WebKeys.HTMLPAGE_EDIT, workingHTMLPage);
        setForward(req, "portlet.ext.director.unlock_htmlpage");
        return;
      } else if (workingHTMLPage.isLocked()) {
        // it's locked by the same user
        WebAssetFactory.unLockAsset(workingHTMLPage);
      }

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/htmlpages/edit_htmlpage"});
      params.put("cmd", new String[] {"edit"});
      params.put("inode", new String[] {workingHTMLPage.getInode() + ""});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }
    if (cmd != null && cmd.equals("viewStatistics")) {

      Logger.debug(DirectorAction.class, "Director :: editHTMLPage");

      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/htmlpageviews/view_htmlpage_views"});
      params.put("htmlpage", new String[] {htmlPage.getInode() + ""});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getRenderURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("editFile")) {

      Logger.debug(DirectorAction.class, "Director :: editFile");

      String fileAssetInode = "";

      if (UtilMethods.isSet(req.getParameter("file"))) fileAssetInode = req.getParameter("file");
      else return;

      Identifier identifier = APILocator.getIdentifierAPI().findFromInode(fileAssetInode);

      if (identifier.getAssetType().equals("contentlet")) {
        try {
          Contentlet cont = APILocator.getContentletAPI().find(fileAssetInode, user, false);

          java.util.Map params = new java.util.HashMap();
          params.put("struts_action", new String[] {"/ext/contentlet/edit_contentlet"});
          params.put("cmd", new String[] {"edit"});
          params.put("inode", new String[] {cont.getInode() + ""});
          params.put("referer", new String[] {referer});

          String af =
              com.dotmarketing.util.PortletURLUtil.getActionURL(
                  httpReq, WindowState.MAXIMIZED.toString(), params);

          _sendToReferral(req, res, af);
        } catch (DotSecurityException e) {
          Logger.error(this, e.getMessage());
          return;
        }
      } else {
        try {
          // gets the current working asset
          WebAsset workingFile =
              (WebAsset)
                  APILocator.getVersionableAPI()
                      .findWorkingVersion(
                          identifier, APILocator.getUserAPI().getSystemUser(), false);

          if ("unlockFile".equals(subcmd)) {
            WebAssetFactory.unLockAsset(workingFile);
          }

          if (workingFile.isLocked() && !workingFile.getModUser().equals(user.getUserId())) {
            req.setAttribute(WebKeys.FILE_EDIT, workingFile);
            setForward(req, "portlet.ext.director.unlock_file");
            return;
          } else if (workingFile.isLocked()) {
            // it's locked by the same user
            WebAssetFactory.unLockAsset(workingFile);
          }

          java.util.Map params = new java.util.HashMap();
          params.put("struts_action", new String[] {"/ext/files/edit_file"});
          params.put("cmd", new String[] {"edit"});
          params.put("inode", new String[] {workingFile.getInode() + ""});
          params.put("referer", new String[] {referer});

          String af =
              com.dotmarketing.util.PortletURLUtil.getActionURL(
                  httpReq, WindowState.MAXIMIZED.toString(), params);

          _sendToReferral(req, res, af);
        } catch (DotStateException e) {
          Logger.error(this, e.getMessage());
          return;
        } catch (DotSecurityException e) {
          Logger.error(this, e.getMessage());
          return;
        }
      }

      return;
    }

    if (cmd != null && cmd.equals("editTemplate")) {

      Logger.debug(DirectorAction.class, "Director :: editTemplate");

      HTMLPage htmlPage = new HTMLPage();
      WebAsset workingTemplate = new Template();
      if (req.getParameter("htmlPage") != null) {
        htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);
        workingTemplate = HTMLPageFactory.getHTMLPageTemplate(htmlPage, true);
      } else if (req.getParameter("template") != null) {
        workingTemplate =
            (Template) InodeFactory.getInode(req.getParameter("template"), Template.class);
      }

      if ("unlockTemplate".equals(subcmd)) {
        WebAssetFactory.unLockAsset(workingTemplate);
      }

      if (workingTemplate.isLocked() && !workingTemplate.getModUser().equals(user.getUserId())) {
        req.setAttribute(WebKeys.HTMLPAGE_EDIT, htmlPage);
        req.setAttribute(WebKeys.TEMPLATE_EDIT, workingTemplate);
        setForward(req, "portlet.ext.director.unlock_template");
        return;
      } else if (workingTemplate.isLocked()) {
        // it's locked by the same user
        WebAssetFactory.unLockAsset(workingTemplate);
      }

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/templates/edit_template"});
      params.put("cmd", new String[] {"edit"});
      params.put("inode", new String[] {workingTemplate.getInode() + ""});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("publishHTMLPage")) {

      Logger.debug(DirectorAction.class, "Director :: publishHTMLPage");

      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/htmlpages/publish_htmlpages"});
      params.put("cmd", new String[] {"prepublish"});
      params.put("publishInode", new String[] {htmlPage.getInode() + ""});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("editContainer")) {

      Logger.debug(DirectorAction.class, "Director :: editContainer" + subcmd);

      Container container =
          (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);

      Identifier identifier = APILocator.getIdentifierAPI().find(container);
      // gets the current working asset
      WebAsset workingContainer =
          (WebAsset)
              APILocator.getVersionableAPI()
                  .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);

      if ("unlockContainer".equals(subcmd)) {
        WebAssetFactory.unLockAsset(workingContainer);
      }
      if (workingContainer.isLocked() && !workingContainer.getModUser().equals(user.getUserId())) {
        req.setAttribute(WebKeys.CONTAINER_EDIT, workingContainer);
        setForward(req, "portlet.ext.director.unlock_container");
        return;
      } else if (workingContainer.isLocked()) {
        // it's locked by the same user
        WebAssetFactory.unLockAsset(workingContainer);
      }
      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/containers/edit_container"});
      params.put("cmd", new String[] {"edit"});
      params.put("inode", new String[] {workingContainer.getInode() + ""});
      params.put("referer", new String[] {referer});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("editLink")) {

      Logger.debug(DirectorAction.class, "Director :: editLink");

      String popup = req.getParameter("popup");
      Link link = (Link) InodeFactory.getInode(req.getParameter("link"), Link.class);

      Identifier identifier = APILocator.getIdentifierAPI().find(link);
      // gets the current working asset
      WebAsset workingLink =
          (WebAsset)
              APILocator.getVersionableAPI()
                  .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);

      if ("unlockLink".equals(subcmd)) {
        WebAssetFactory.unLockAsset(workingLink);
      }
      if (workingLink.isLocked() && !workingLink.getModUser().equals(user.getUserId())) {
        req.setAttribute(WebKeys.LINK_EDIT, workingLink);
        if (UtilMethods.isSet(popup)) {
          Logger.debug(DirectorAction.class, "Going to SIX I have popup!!!!!!!!!!!!!!!!");
          setForward(req, "portlet.ext.director.unlock_popup_link");
          return;
        } else {
          Logger.debug(DirectorAction.class, "Going to FIVE I dont have popup!!!!!!!!!!!!!!!!");
          setForward(req, "portlet.ext.director.unlock_link");
          return;
        }
      } else if (workingLink.isLocked()) {
        // it's locked by the same user
        WebAssetFactory.unLockAsset(workingLink);
      }
      String popURL = "";
      if (UtilMethods.isSet(popup)) {
        popURL = "_popup";
      }
      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/links/edit_link"});
      params.put("cmd", new String[] {"edit"});
      params.put("inode", new String[] {workingLink.getInode() + ""});
      params.put("popup", new String[] {popup});
      params.put("referer", new String[] {referer});
      params.put(
          "child",
          new String[] {(req.getParameter("child") != null) ? req.getParameter("child") : ""});
      params.put(
          "page_width",
          new String[] {
            (req.getParameter("page_width") != null) ? req.getParameter("page_width") : ""
          });
      params.put(
          "browse",
          new String[] {(req.getParameter("browse") != null) ? req.getParameter("browse") : ""});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    if (cmd != null && cmd.equals("addChild")) {

      try {
        Logger.debug(DirectorAction.class, "Director :: addChild");

        HibernateUtil.startTransaction();

        Contentlet contentlet = new Contentlet();
        String cInode = req.getParameter("contentlet");
        if (InodeUtils.isSet(cInode)) {
          contentlet = conAPI.find(cInode, user, true);
        }
        Container container =
            (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);
        HTMLPage htmlPage =
            (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

        boolean hasPermissionOnContainer =
            perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false);
        if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
          hasPermissionOnContainer = true;

        boolean hasPermissionsOnPage =
            perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false);
        boolean duplicateContentCheck = false;

        if (!hasPermissionOnContainer || !hasPermissionsOnPage) {
          throw new DotSecurityException(
              "User has no permission to add content on container = "
                  + req.getParameter("container")
                  + " on page = "
                  + req.getParameter("htmlPage"));
        }

        Identifier identifier = APILocator.getIdentifierAPI().find(contentlet);

        Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find(htmlPage);
        Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container);

        if (InodeUtils.isSet(identifier.getInode())
            && InodeUtils.isSet(htmlPageIdentifier.getInode())
            && InodeUtils.isSet(containerIdentifier.getInode())) {
          MultiTree mTree =
              new MultiTree(
                  htmlPageIdentifier.getInode(),
                  containerIdentifier.getInode(),
                  identifier.getInode());
          java.util.List<MultiTree> treeList = MultiTreeFactory.getMultiTree(htmlPage, container);
          for (int i = 0; i < treeList.size(); i++) {
            if (treeList.get(i).getChild().equals(identifier.getInode())) {
              duplicateContentCheck = true;
              session.setAttribute(
                  "duplicatedErrorMessage",
                  "Content already exists in the same container on the page");
            }
          }
          if (!duplicateContentCheck) {
            MultiTreeFactory.saveMultiTree(mTree);

            // Updating the last mod user and last mod date of the page
            htmlPage.setModDate(new Date());
            htmlPage.setModUser(user.getUserId());
            HibernateUtil.saveOrUpdate(htmlPage);
          }

        } else {
          Logger.error(
              this,
              "Error found trying to associate the contentlet inode: "
                  + contentlet.getInode()
                  + "(iden: "
                  + identifier.getInode()
                  + ") "
                  + "to the container: "
                  + container.getInode()
                  + "(iden: "
                  + containerIdentifier.getInode()
                  + ") "
                  + "of the page: "
                  + htmlPage.getInode()
                  + "(iden: "
                  + htmlPageIdentifier.getInode()
                  + ") "
                  + "the system was unable to find some the identifiers (tree error?)!");
        }

      } catch (DotRuntimeException e) {
        Logger.error(this, "Unable to add content to page", e);
      } finally {
        try {
          HibernateUtil.commitTransaction();
        } catch (Exception e) {
          session.setAttribute(
              "duplicatedErrorMessage", "Content already exists in the same container on the page");
          // res.sendRedirect(referer);
        }
      }
      _sendToReferral(req, res, referer);
      return;
    }

    if (cmd != null && cmd.equals("removeChild")) {

      try {

        Logger.debug(DirectorAction.class, "Director :: removeChild");

        HibernateUtil.startTransaction();

        Contentlet contentlet = new Contentlet();
        String cInode = req.getParameter("contentlet");
        if (InodeUtils.isSet(cInode)) {
          contentlet = conAPI.find(cInode, user, true);
        }
        Container container =
            (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);
        HTMLPage htmlPage =
            (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

        boolean hasPermissionOnPage =
            perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false);
        boolean hasPermissionOnContainer =
            perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false);
        if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
          hasPermissionOnContainer = true;

        if (!hasPermissionOnContainer || !hasPermissionOnPage) {
          throw new DotSecurityException(
              "User has no permission to remove content from container = "
                  + req.getParameter("container")
                  + " on page = "
                  + req.getParameter("htmlPage"));
        }

        Identifier identifier = APILocator.getIdentifierAPI().find(contentlet);
        Logger.debug(
            DirectorAction.class,
            "Identifier of Contentlet to be removed=" + identifier.getInode());

        Contentlet contentletWorking =
            conAPI.findContentletByIdentifier(
                identifier.getInode(), false, contentlet.getLanguageId(), user, true);
        Contentlet liveContentlet =
            conAPI.findContentletByIdentifier(
                identifier.getInode(), false, contentlet.getLanguageId(), user, true);
        Logger.debug(
            DirectorAction.class,
            "\n\nContentlet Working to be removed=" + contentletWorking.getInode());

        Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find(htmlPage);
        Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container);
        MultiTree multiTree =
            MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier, identifier);
        Logger.debug(DirectorAction.class, "multiTree=" + multiTree);
        MultiTreeFactory.deleteMultiTree(multiTree);

        // Updating the last mod user and last mod date of the page
        htmlPage.setModDate(new Date());
        htmlPage.setModUser(user.getUserId());
        HibernateUtil.saveOrUpdate(htmlPage);
      } catch (DotRuntimeException e) {
        Logger.error(this, "Unable to remove content from page", e);
      } finally {
        HibernateUtil.commitTransaction();
      }
      _sendToReferral(req, res, referer);
      return;
    }

    if (cmd != null && cmd.equals("makeHomePage")) {

      Logger.debug(DirectorAction.class, "Director :: makeHomePage");

      if (InodeUtils.isSet(req.getParameter("htmlPage"))) {
        HTMLPage htmlPage =
            (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);
        Folder folder = APILocator.getFolderAPI().findParentFolder(htmlPage, user, false);

        UserPreference up =
            UserPreferencesFactory.getUserPreferenceValue(
                user.getUserId(), WebKeys.USER_PREFERENCE_HOME_PAGE);

        if (up.getId() > 0) {
          up.setValue(htmlPage.getURI(folder));

        } else {
          up.setUserId(user.getUserId());
          up.setPreference(WebKeys.USER_PREFERENCE_HOME_PAGE);
          up.setValue(htmlPage.getURI(folder));
        }
        UserPreferencesFactory.saveUserPreference(up);
      } else {
        // the user clicked on set with no page that means unsetting the page
        UserPreferencesFactory.deleteUserPreference(
            user.getUserId(), WebKeys.USER_PREFERENCE_HOME_PAGE);
      }

      _sendToReferral(req, res, referer);
      return;
    }

    if (cmd != null && cmd.equals("moveUp")) {

      Logger.debug(DirectorAction.class, "Director :: moveUp");
      Contentlet contentlet = new Contentlet();
      String cInode = req.getParameter("contentlet");
      if (InodeUtils.isSet(cInode)) {
        contentlet = conAPI.find(cInode, user, true);
      }
      Container container =
          (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);
      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

      boolean hasPermissionOnPage =
          perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false);
      boolean hasPermissionOnContainer =
          perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false);
      if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
        hasPermissionOnContainer = true;

      if (!hasPermissionOnContainer || !hasPermissionOnPage) {
        throw new DotSecurityException(
            "User has no permission to reorder content on container = "
                + req.getParameter("container")
                + " on page = "
                + req.getParameter("htmlPage"));
      }

      String staticContainer = req.getParameter("static");

      Logger.debug(DirectorAction.class, "staticContainer=" + staticContainer);

      java.util.List cletList = new ArrayList();
      String sort =
          (container.getSortContentletsBy() == null)
              ? "tree_order"
              : container.getSortContentletsBy();

      Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
      Identifier idenContainer = APILocator.getIdentifierAPI().find(container);
      cletList =
          conAPI.findPageContentlets(
              idenHtmlPage.getInode(),
              idenContainer.getInode(),
              sort,
              true,
              contentlet.getLanguageId(),
              user,
              false);
      Logger.debug(DirectorAction.class, "Number of contentlets = " + cletList.size());

      int newPosition = cletList.indexOf(contentlet) - 1;

      if (newPosition >= 0) {

        idenContainer = APILocator.getIdentifierAPI().find(container);
        idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
        int x = 0;
        Iterator i = cletList.iterator();

        while (i.hasNext()) {

          Identifier iden;
          MultiTree multiTree;
          Contentlet c = (Contentlet) i.next();

          Logger.debug(DirectorAction.class, "Contentlet inode = " + c.getInode());

          if (newPosition == x) {
            iden = APILocator.getIdentifierAPI().find(contentlet);
            multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden);
            multiTree.setTreeOrder(x);
            MultiTreeFactory.saveMultiTree(multiTree);
            x++;
          }

          if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) {
            iden = APILocator.getIdentifierAPI().find(c);
            multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden);
            multiTree.setTreeOrder(x);
            MultiTreeFactory.saveMultiTree(multiTree);
            x++;
          }
        }
      }
      _sendToReferral(req, res, referer);
      return;
    }

    if (cmd != null && cmd.equals("moveDown")) {

      Logger.debug(DirectorAction.class, "Director :: moveDown");
      Contentlet contentlet = new Contentlet();
      String cInode = req.getParameter("contentlet");
      if (InodeUtils.isSet(cInode)) {
        contentlet = conAPI.find(cInode, user, true);
      }
      Container container =
          (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);
      HTMLPage htmlPage =
          (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);
      String staticContainer = req.getParameter("static");

      boolean hasPermissionOnPage =
          perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false);
      boolean hasPermissionOnContainer =
          perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false);
      if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
        hasPermissionOnContainer = true;

      if (!hasPermissionOnContainer || !hasPermissionOnPage) {
        throw new DotSecurityException(
            "User has no permission to reorder content on container = "
                + req.getParameter("container")
                + " on page = "
                + req.getParameter("htmlPage"));
      }
      Logger.debug(DirectorAction.class, "staticContainer=" + staticContainer);

      java.util.List cletList = new ArrayList();
      String sort =
          (container.getSortContentletsBy() == null)
              ? "tree_order"
              : container.getSortContentletsBy();

      Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
      Identifier idenContainer = APILocator.getIdentifierAPI().find(container);
      cletList =
          conAPI.findPageContentlets(
              idenHtmlPage.getInode(),
              idenContainer.getInode(),
              sort,
              true,
              contentlet.getLanguageId(),
              user,
              false);
      Logger.debug(DirectorAction.class, "Number of contentlets = " + cletList.size());

      int newPosition = cletList.indexOf(contentlet) + 1;

      if (newPosition < cletList.size()) {

        idenContainer = APILocator.getIdentifierAPI().find(container);
        idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
        int x = 0;
        Iterator i = cletList.iterator();

        while (i.hasNext()) {

          Identifier iden;
          MultiTree multiTree;
          Contentlet c = (Contentlet) i.next();

          Logger.debug(DirectorAction.class, "Contentlet inode = " + c.getInode());

          if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) {
            iden = APILocator.getIdentifierAPI().find(c);
            multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden);
            multiTree.setTreeOrder(x);
            MultiTreeFactory.saveMultiTree(multiTree);
            x++;
          }

          if (newPosition == x) {
            iden = APILocator.getIdentifierAPI().find(contentlet);
            multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden);
            multiTree.setTreeOrder(x);
            MultiTreeFactory.saveMultiTree(multiTree);
            x++;
          }
        }
      }

      _sendToReferral(req, res, referer);
      return;
    }

    if (cmd != null && cmd.equals("unlock")) {

      Logger.debug(DirectorAction.class, "Director :: unlock Contentlet");

      Contentlet contentlet = new Contentlet();
      String cInode = req.getParameter("contentlet");
      if (InodeUtils.isSet(cInode)) {
        contentlet = conAPI.find(cInode, user, true);
      }
      conAPI.unlock(contentlet, user, true);
    }

    if (cmd != null && cmd.equals("createForm")) {

      Logger.debug(DirectorAction.class, "Director :: createForrm");
      java.util.Map params = new java.util.HashMap();
      params.put("struts_action", new String[] {"/ext/structure/edit_structure"});
      params.put("structureType", new String[] {Integer.toString(Structure.STRUCTURE_TYPE_FORM)});
      params.put("cmd", new String[] {"null"});

      String af =
          com.dotmarketing.util.PortletURLUtil.getActionURL(
              httpReq, WindowState.MAXIMIZED.toString(), params);

      _sendToReferral(req, res, af);
      return;
    }

    Contentlet contentlet = new Contentlet();
    String cInode = req.getParameter("contentlet");
    if (InodeUtils.isSet(cInode)) {
      contentlet = conAPI.find(cInode, user, true);
    }
    if (contentlet == null) {
      throw new DotStateException("Trying to edit an invalid contentlet - inode:" + cInode);
    }
    Container container =
        (Container) InodeFactory.getInode(req.getParameter("container"), Container.class);
    HTMLPage htmlPage =
        (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class);

    Logger.debug(DirectorAction.class, "contentlet=" + contentlet.getInode());

    String contentletInode = "";
    if (InodeUtils.isSet(contentlet.getInode())) {

      Identifier identifier = APILocator.getIdentifierAPI().find(contentlet);
      // gets the current working asset
      Contentlet workingContentlet =
          conAPI.findContentletByIdentifier(
              identifier.getInode(), false, contentlet.getLanguageId(), user, false);

      Logger.debug(DirectorAction.class, "workingContentlet=" + workingContentlet.getInode());
      Logger.debug(
          DirectorAction.class, "workingContentlet.getModUser()=" + workingContentlet.getModUser());
      Logger.debug(
          DirectorAction.class, "workingContentlet.isLocked()=" + workingContentlet.isLocked());

      contentletInode = workingContentlet.getInode();
    } else {
      contentletInode = contentlet.getInode();
    }

    Logger.debug(DirectorAction.class, "Director :: Edit Contentlet");

    java.util.Map params = new java.util.HashMap();
    params.put("struts_action", new String[] {"/ext/contentlet/edit_contentlet"});

    String cmdAux = (cmd.equals("newedit") ? cmd : "edit");

    params.put("cmd", new String[] {cmdAux});
    params.put("htmlpage_inode", new String[] {htmlPage.getInode() + ""});
    params.put("contentcontainer_inode", new String[] {container.getInode() + ""});
    params.put("inode", new String[] {contentletInode + ""});
    if (InodeUtils.isSet(req.getParameter("selectedStructure"))) {
      params.put("selectedStructure", new String[] {req.getParameter("selectedStructure") + ""});
    }
    params.put(
        "lang",
        new String[] {(req.getParameter("language") != null) ? req.getParameter("language") : ""});
    params.put("referer", new String[] {referer});

    String af =
        com.dotmarketing.util.PortletURLUtil.getActionURL(
            httpReq, WindowState.MAXIMIZED.toString(), params);

    _sendToReferral(req, res, af);
    return;
  }