public void init(ServletConfig config) throws ServletException {

    // build the dirs
    new File(config.getServletContext().getRealPath("/WEB-INF/velocity/working")).mkdirs();
    new File(config.getServletContext().getRealPath("/WEB-INF/velocity/live")).mkdir();

    Config.initializeConfig();
    CHARSET = Config.getStringProperty("CHARSET");
    VELOCITY_HTMLPAGE_EXTENSION = Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION");
  }
Exemple #2
0
  private void loadConfig() {

    Iterator<String> it = Config.getKeys();
    while (it.hasNext()) {
      String key = it.next();
      if (key == null) continue;
      if (key.startsWith("es.")) {
        // if we already have a key, use it
        if (System.getProperty(key) == null) {
          System.setProperty(key, Config.getStringProperty(key));
        }
      }
    }
  }
  public void init(Object obj) {
    if (!Config.getBooleanProperty("ENABLE_SCRIPTING", false)) {
      return;
    }
    ViewContext context = (ViewContext) obj;

    this.request = context.getRequest();
    ctx = context.getVelocityContext();
    try {
      host = WebAPILocator.getHostWebAPI().getCurrentHost(request);
    } catch (PortalException e1) {
      Logger.error(this, e1.getMessage(), e1);
    } catch (SystemException e1) {
      Logger.error(this, e1.getMessage(), e1);
    } catch (DotDataException e1) {
      Logger.error(this, e1.getMessage(), e1);
    } catch (DotSecurityException e1) {
      Logger.error(this, e1.getMessage(), e1);
    }
    userAPI = WebAPILocator.getUserWebAPI();
    try {
      user = userAPI.getLoggedInFrontendUser(request);
      backuser = userAPI.getLoggedInUser(request);
      respectFrontendRoles = true;
    } catch (Exception e) {
      Logger.error(this, "Error finding the logged in user", e);
    }
  }
Exemple #4
0
  @SuppressWarnings("rawtypes")
  @Override
  public List<Class> getBundlers() {
    boolean buildCategories = false;
    for (PublishQueueElement element : ((PushPublisherConfig) config).getAssets())
      if (element.getType().equals("category")) buildCategories = true;
    List<Class> list = new ArrayList<Class>();

    // The order is important cause
    // I need to add all containers associated with templates

    /** ISSUE #2244: https://github.com/dotCMS/dotCMS/issues/2244 */
    if (buildCategories) list.add(CategoryBundler.class);
    else {
      list.add(DependencyBundler.class);
      list.add(HostBundler.class);
      list.add(ContentBundler.class);
      list.add(FolderBundler.class);
      list.add(TemplateBundler.class);
      list.add(ContainerBundler.class);
      list.add(HTMLPageBundler.class);
      list.add(LinkBundler.class);

      if (Config.getBooleanProperty("PUSH_PUBLISHING_PUSH_STRUCTURES")) {
        list.add(StructureBundler.class);
        /** ISSUE #2222: https://github.com/dotCMS/dotCMS/issues/2222 */
        list.add(RelationshipBundler.class);
      }
      list.add(LanguageBundler.class);
    }

    return list;
  }
Exemple #5
0
 public static void removePageFile(HTMLPage htmlPage, Identifier identifier, boolean EDIT_MODE) {
   String folderPath =
       (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator;
   String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
   if (velocityRootPath.startsWith("/WEB-INF")) {
     velocityRootPath = com.liferay.util.FileUtil.getRealPath(velocityRootPath);
   }
   String filePath =
       folderPath
           + identifier.getInode()
           + "."
           + Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION");
   velocityRootPath += java.io.File.separator;
   java.io.File f = new java.io.File(velocityRootPath + filePath);
   f.delete();
   DotResourceCache vc = CacheLocator.getVeloctyResourceCache();
   vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath);
   CacheLocator.getHTMLPageCache().remove((HTMLPage) htmlPage);
 }
 public static void removeContainerFile(
     Container container, Identifier identifier, boolean EDIT_MODE) {
   String folderPath =
       (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator;
   String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
   if (velocityRootPath.startsWith("/WEB-INF")) {
     velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath);
   }
   velocityRootPath += java.io.File.separator;
   String filePath =
       folderPath
           + identifier.getInode()
           + "."
           + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION");
   java.io.File f = new java.io.File(velocityRootPath + filePath);
   f.delete();
   DotResourceCache vc = CacheLocator.getVeloctyResourceCache();
   vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath);
 }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;

    String sessionid = request.getSession().getId();

    String cookiesSecureFlag = Config.getStringProperty("COOKIES_SECURE_FLAG", "https");

    String cookiesHttpOnly =
        Config.getBooleanProperty("COOKIES_HTTP_ONLY", true) ? "; HttpOnly;" : "";

    if (cookiesSecureFlag.equals("always")) {
      response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure" + cookiesHttpOnly);
    } else if (cookiesSecureFlag.equals("https") && req.isSecure()) {
      response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure" + cookiesHttpOnly);
    }

    chain.doFilter(req, response);
  }
Exemple #8
0
  public void init(Object obj) {
    if (!Config.getBooleanProperty("ENABLE_SCRIPTING", false)) {
      return;
    }

    ViewContext context = (ViewContext) obj;

    this.request = context.getRequest();
    ctx = context.getVelocityContext();
    this.request = context.getRequest();
    this.response = context.getResponse();
  }
Exemple #9
0
  private void initNode() {
    String node_id = "dotCMS_" + Config.getStringProperty("DIST_INDEXATION_SERVER_ID");
    _nodeInstance =
        nodeBuilder()
            .settings(ImmutableSettings.settingsBuilder().put("name", node_id).build())
            .build()
            .start();
    try {
      // wait a bit while the node gets available for requests
      Thread.sleep(5000L);
    } catch (InterruptedException e) {

    }
  }
Exemple #10
0
 public NavResult(String parent, String hostId, String folderId) {
   this.hostId = hostId;
   this.folderId = folderId;
   this.parent = parent;
   hrefVelocity = false;
   title = href = "";
   order = 0;
   checkPermissions = Config.getBooleanProperty("ENABLE_NAV_PERMISSION_CHECK", false);
   try {
     sysuser = APILocator.getUserAPI().getSystemUser();
   } catch (DotDataException e) {
     Logger.warn(this, e.getMessage(), e);
   }
 }
Exemple #11
0
  protected boolean canUserEvalute() throws DotDataException, DotSecurityException {
    if (!Config.getBooleanProperty("ENABLE_SCRIPTING", false)) {
      Logger.warn(this.getClass(), "Scripting called and ENABLE_SCRIPTING set to false");
      return false;
    }
    ica = new InternalContextAdapterImpl(ctx);
    String fieldResourceName = ica.getCurrentTemplateName();
    String inode = null;
    String userId = null;
    if (fieldResourceName.indexOf("field") > -1) {
      inode =
          fieldResourceName.substring(
              fieldResourceName.lastIndexOf("/") + 1, fieldResourceName.indexOf("_"));
      Contentlet con =
          APILocator.getContentletAPI().find(inode, APILocator.getUserAPI().getSystemUser(), true);
      userId = con.getModUser();
    } else if (fieldResourceName.indexOf("template") > -1) {
      inode =
          fieldResourceName.substring(
              fieldResourceName.lastIndexOf("/") + 1, fieldResourceName.indexOf("."));
      Template t =
          APILocator.getTemplateAPI()
              .findWorkingTemplate(inode, APILocator.getUserAPI().getSystemUser(), true);
      userId = t.getModUser();
      if (isWarned < 5) {
        Logger.warn(this.getClass(), "calling $jsp.include from a template results in a db hit");
        isWarned++;
      }

    } else if (fieldResourceName.indexOf("container") > -1) {
      inode =
          fieldResourceName.substring(
              fieldResourceName.lastIndexOf("/") + 1, fieldResourceName.indexOf("."));
      Container c =
          APILocator.getContainerAPI()
              .getWorkingContainerById(inode, APILocator.getUserAPI().getSystemUser(), true);
      userId = c.getModUser();
      if (isWarned < 5) {
        Logger.warn(this.getClass(), "calling $jsp.include from a container results in a db hit");
        isWarned++;
      }
    }
    if (userId == null) {
      return false;
    }
    User mu =
        APILocator.getUserAPI().loadUserById(userId, APILocator.getUserAPI().getSystemUser(), true);
    Role scripting = APILocator.getRoleAPI().loadRoleByKey("Scripting Developer");
    return APILocator.getRoleAPI().doesUserHaveRole(mu, scripting);
  }
 protected boolean canUserEvalute() throws DotDataException, DotSecurityException {
   if (!Config.getBooleanProperty("ENABLE_SCRIPTING", false)) {
     Logger.warn(this.getClass(), "Scripting called and ENABLE_SCRIPTING set to false");
     return false;
   }
   ica = new InternalContextAdapterImpl(ctx);
   String fieldResourceName = ica.getCurrentTemplateName();
   String conInode =
       fieldResourceName.substring(
           fieldResourceName.indexOf("/") + 1, fieldResourceName.indexOf("_"));
   Contentlet con =
       APILocator.getContentletAPI().find(conInode, APILocator.getUserAPI().getSystemUser(), true);
   User mu = userAPI.loadUserById(con.getModUser(), APILocator.getUserAPI().getSystemUser(), true);
   Role scripting = APILocator.getRoleAPI().loadRoleByKey("Scripting Developer");
   return APILocator.getRoleAPI().doesUserHaveRole(mu, scripting);
 }
Exemple #13
0
  public String get(String key, String languageId) {
    String value = null;
    try {
      Language lang = langAPI.getLanguage(languageId);
      value = langAPI.getStringKey(lang, key);

      if ((!UtilMethods.isSet(value) || value.equals(key))
          && Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE")) {
        lang = langAPI.getDefaultLanguage();
        value = langAPI.getStringKey(lang, key);
      }
    } catch (Exception e) {
      Logger.error(this, e.toString());
    }

    return (value == null) ? "" : value;
  }
  public void executeUpgrade() throws DotDataException, DotRuntimeException {
    DotConnect dc = new DotConnect();

    try {
      DbConnectionFactory.getConnection().setAutoCommit(true);
    } catch (SQLException e) {
      Logger.warn(this.getClass(), e.getMessage(), e);
    }

    if (Config.getBooleanProperty("upgrade-cleanup-bad-data", true)) {
      final String[] smts =
          new String[] {
            "delete from inode where type='folder' and not exists (select * from folder where folder.inode=inode.inode)",
            "delete from inode where type='contentlet' and not exists (select * from contentlet where contentlet.inode=inode.inode)",
            "delete from inode where type='file_asset' and not exists (select * from file_asset where file_asset.inode=inode.inode)",
            "delete from inode where type='containers' and not exists (select * from containers where containers.inode=inode.inode)",
            "delete from inode where type='template' and not exists (select * from template where template.inode=inode.inode)",
            "delete from inode where type='htmlpage' and not exists (select * from htmlpage where htmlpage.inode=inode.inode)",
            "delete from inode where type='containers' and not exists (select * from containers where containers.inode=inode.inode)",
            "delete from inode where type='links' and not exists (select * from links where links.inode=inode.inode)",
            "delete from identifier where not exists (select * from inode where inode.identifier=identifier.inode)"
          };

      for (String smt : smts) {
        try {
          dc.executeStatement(smt);
        } catch (SQLException e) {
          Logger.warn(this.getClass(), e.getMessage());
        }
      }
    }

    try {
      dc.executeStatement("delete from dist_reindex_journal");
    } catch (SQLException e) {
      Logger.warn(this, "can't clean dist_reindex_journal");
    }
  }
  public void doLiveMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration());
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    // Map with all identifier inodes for a given uri.
    String idInode = APILocator.getIdentifierAPI().find(host, uri).getInode();

    // Checking the path is really live using the livecache
    String cachedUri = LiveCache.getPathFromCache(uri, host);

    // if we still have nothing.
    if (!InodeUtils.isSet(idInode) || cachedUri == null) {
      throw new ResourceNotFoundException(
          String.format("Resource %s not found in Live mode!", uri));
    }

    response.setContentType(CHARSET);

    request.setAttribute("idInode", String.valueOf(idInode));
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + idInode);

    /*
     * JIRA http://jira.dotmarketing.net/browse/DOTCMS-4659
    //Set long lived cookie regardless of who this is */
    String _dotCMSID =
        UtilMethods.getCookieValue(
            request.getCookies(), com.dotmarketing.util.WebKeys.LONG_LIVED_DOTCMS_ID_COOKIE);

    if (!UtilMethods.isSet(_dotCMSID)) {
      // create unique generator engine
      Cookie idCookie = CookieUtil.createCookie();
      response.addCookie(idCookie);
    }

    com.liferay.portal.model.User user = null;
    HttpSession session = request.getSession(false);
    try {
      if (session != null)
        user =
            (com.liferay.portal.model.User)
                session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying to getUser: "******"Page Permissions for URI=" + uri);

    HTMLPage page = null;
    try {
      // we get the page and check permissions below
      page =
          APILocator.getHTMLPageAPI()
              .loadLivePageById(idInode, APILocator.getUserAPI().getSystemUser(), false);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return;
    }

    // Check if the page is visible by a CMS Anonymous role
    if (!permissionAPI.doesUserHavePermission(page, PERMISSION_READ, user, true)) {
      // this page is protected. not anonymous access

      /**
       * ***************************************************************** If we need to redirect
       * someone somewhere to login before seeing a page, we need to edit the /portal/401.jsp page
       * to sendRedirect the user to the proper login page. We are not using the REDIRECT_TO_LOGIN
       * variable in the config any longer.
       * ****************************************************************
       */
      if (!signedIn) {
        // No need for the below LAST_PATH attribute on the front end
        // http://jira.dotmarketing.net/browse/DOTCMS-2675
        // request.getSession().setAttribute(WebKeys.LAST_PATH,
        // new ObjectValuePair(uri, request.getParameterMap()));
        request.getSession().setAttribute(com.dotmarketing.util.WebKeys.REDIRECT_AFTER_LOGIN, uri);

        Logger.debug(
            VelocityServlet.class,
            "VELOCITY CHECKING PERMISSION: Page doesn't have anonymous access" + uri);

        Logger.debug(VelocityServlet.class, "401 URI = " + uri);

        Logger.debug(VelocityServlet.class, "Unauthorized URI = " + uri);
        response.sendError(401, "The requested page/file is unauthorized");
        return;

      } else if (!permissionAPI
          .getReadRoles(ident)
          .contains(APILocator.getRoleAPI().loadLoggedinSiteRole())) {
        // user is logged in need to check user permissions
        Logger.debug(VelocityServlet.class, "VELOCITY CHECKING PERMISSION: User signed in");

        // check user permissions on this asset
        if (!permissionAPI.doesUserHavePermission(ident, PERMISSION_READ, user, true)) {
          // the user doesn't have permissions to see this page
          // go to unauthorized page
          Logger.warn(
              VelocityServlet.class,
              "VELOCITY CHECKING PERMISSION: Page doesn't have any access for this user");
          response.sendError(403, "The requested page/file is forbidden");
          return;
        }
      }
    }

    Logger.debug(VelocityServlet.class, "Recording the ClickStream");
    if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) {
      if (user != null) {
        UserProxy userProxy =
            com.dotmarketing.business.APILocator.getUserProxyAPI()
                .getUserProxy(user, APILocator.getUserAPI().getSystemUser(), false);
        if (!userProxy.isNoclicktracking()) {
          ClickstreamFactory.addRequest(
              (HttpServletRequest) request, ((HttpServletResponse) response), host);
        }
      } else {
        ClickstreamFactory.addRequest(
            (HttpServletRequest) request, ((HttpServletResponse) response), host);
      }
    }

    // Begin Page Caching
    boolean buildCache = false;
    String key = getPageCacheKey(request);
    if (key != null) {

      String cachedPage = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL());

      if (cachedPage == null
          || "refresh".equals(request.getParameter("dotcache"))
          || "refresh".equals(request.getAttribute("dotcache"))
          || "refresh".equals(request.getSession().getAttribute("dotcache"))) {
        // build cached response
        buildCache = true;
      } else {
        // have cached response and are not refreshing, send it
        response.getWriter().write(cachedPage);
        return;
      }
    }

    Writer out =
        (buildCache) ? new StringWriter(4096) : new VelocityFilterWriter(response.getWriter());

    // get the context from the requst if possible
    Context context = VelocityUtil.getWebContext(request, response);

    request.setAttribute("velocityContext", context);
    Logger.debug(VelocityServlet.class, "HTMLPage Identifier:" + idInode);

    try {

      VelocityUtil.getEngine()
          .getTemplate("/live/" + idInode + "." + VELOCITY_HTMLPAGE_EXTENSION)
          .merge(context, out);

    } catch (ParseErrorException e) {
      // out.append(e.getMessage());
    }

    context = null;
    if (buildCache) {
      String trimmedPage = out.toString().trim();
      response.getWriter().write(trimmedPage);
      response.getWriter().close();
      synchronized (key) {
        String x = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL());
        if (x != null) {
          return;
        }
        CacheLocator.getBlockDirectiveCache()
            .add(getPageCacheKey(request), trimmedPage, (int) page.getCacheTTL());
      }
    } else {
      out.close();
    }
  }
Exemple #16
0
  @Override
  public PublisherConfig process(final PublishStatus status) throws DotPublishingException {
    if (LicenseUtil.getLevel() < 400)
      throw new RuntimeException("need an enterprise prime license to run this bundler");

    PublishAuditHistory currentStatusHistory = null;
    try {
      // Compressing bundle
      File bundleRoot = BundlerUtil.getBundleRoot(config);

      ArrayList<File> list = new ArrayList<File>(1);
      list.add(bundleRoot);
      File bundle =
          new File(
              bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz");
      PushUtils.compressFiles(list, bundle, bundleRoot.getAbsolutePath());

      // Retriving enpoints and init client
      List<PublishingEndPoint> endpoints = ((PushPublisherConfig) config).getEndpoints();
      Map<String, List<PublishingEndPoint>> endpointsMap =
          new HashMap<String, List<PublishingEndPoint>>();
      List<PublishingEndPoint> buffer = null;
      // Organize the endpoints grouping them by groupId
      for (PublishingEndPoint pEndPoint : endpoints) {

        String gid =
            UtilMethods.isSet(pEndPoint.getGroupId()) ? pEndPoint.getGroupId() : pEndPoint.getId();

        if (endpointsMap.get(gid) == null) buffer = new ArrayList<PublishingEndPoint>();
        else buffer = endpointsMap.get(gid);

        buffer.add(pEndPoint);

        // put in map with either the group key or the id if no group is set
        endpointsMap.put(gid, buffer);
      }

      ClientConfig cc = new DefaultClientConfig();

      if (Config.getStringProperty("TRUSTSTORE_PATH") != null
          && !Config.getStringProperty("TRUSTSTORE_PATH").trim().equals(""))
        cc.getProperties()
            .put(
                HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(tFactory.getHostnameVerifier(), tFactory.getSSLContext()));
      Client client = Client.create(cc);

      // Updating audit table
      currentStatusHistory = pubAuditAPI.getPublishAuditStatus(config.getId()).getStatusPojo();

      currentStatusHistory.setPublishStart(new Date());
      pubAuditAPI.updatePublishAuditStatus(
          config.getId(), PublishAuditStatus.Status.SENDING_TO_ENDPOINTS, currentStatusHistory);
      // Increment numTries
      currentStatusHistory.addNumTries();

      boolean hasError = false;
      int errorCounter = 0;

      for (String group : endpointsMap.keySet()) {
        List<PublishingEndPoint> groupList = endpointsMap.get(group);

        boolean sent = false;
        for (PublishingEndPoint endpoint : groupList) {
          EndpointDetail detail = new EndpointDetail();
          try {
            FormDataMultiPart form = new FormDataMultiPart();
            form.field(
                "AUTH_TOKEN",
                retriveKeyString(
                    PublicEncryptionFactory.decryptString(endpoint.getAuthKey().toString())));

            form.field(
                "GROUP_ID",
                UtilMethods.isSet(endpoint.getGroupId())
                    ? endpoint.getGroupId()
                    : endpoint.getId());

            form.field("ENDPOINT_ID", endpoint.getId());
            form.bodyPart(
                new FileDataBodyPart("bundle", bundle, MediaType.MULTIPART_FORM_DATA_TYPE));

            // Sending bundle to endpoint
            WebResource resource =
                client.resource(endpoint.toURL() + "/api/bundlePublisher/publish");

            ClientResponse response =
                resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);

            if (response.getClientResponseStatus().getStatusCode() == HttpStatus.SC_OK) {
              detail.setStatus(PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY.getCode());
              detail.setInfo("Everything ok");
              sent = true;
            } else {
              detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());
              detail.setInfo(
                  "Returned "
                      + response.getClientResponseStatus().getStatusCode()
                      + " status code "
                      + "for the endpoint "
                      + endpoint.getId()
                      + "with address "
                      + endpoint.getAddress());
            }
          } catch (Exception e) {
            hasError = true;
            detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());

            String error =
                "An error occured for the endpoint "
                    + endpoint.getId()
                    + " with address "
                    + endpoint.getAddress()
                    + ".  Error: "
                    + e.getMessage();

            detail.setInfo(error);

            Logger.error(this.getClass(), error);
          }

          currentStatusHistory.addOrUpdateEndpoint(group, endpoint.getId(), detail);

          if (sent) break;
        }

        if (!sent) {
          hasError = true;
          errorCounter++;
        }
      }

      if (!hasError) {
        // Updating audit table
        currentStatusHistory.setPublishEnd(new Date());
        pubAuditAPI.updatePublishAuditStatus(
            config.getId(),
            PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY,
            currentStatusHistory);

        // Deleting queue records
        // pubAPI.deleteElementsFromPublishQueueTable(config.getId());
      } else {
        if (errorCounter == endpointsMap.size()) {
          pubAuditAPI.updatePublishAuditStatus(
              config.getId(),
              PublishAuditStatus.Status.FAILED_TO_SEND_TO_ALL_GROUPS,
              currentStatusHistory);
        } else {
          pubAuditAPI.updatePublishAuditStatus(
              config.getId(),
              PublishAuditStatus.Status.FAILED_TO_SEND_TO_SOME_GROUPS,
              currentStatusHistory);
        }
      }

      return config;

    } catch (Exception e) {
      // Updating audit table
      try {
        pubAuditAPI.updatePublishAuditStatus(
            config.getId(), PublishAuditStatus.Status.FAILED_TO_PUBLISH, currentStatusHistory);
      } catch (DotPublisherException e1) {
        throw new DotPublishingException(e.getMessage());
      }

      Logger.error(this.getClass(), e.getMessage(), e);
      throw new DotPublishingException(e.getMessage());
    }
  }
  @SuppressWarnings("unchecked")
  public ActionForward unspecified(
      ActionMapping rMapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ActionErrors errors = new ActionErrors();
    // Email parameters
    HttpSession session = request.getSession();
    Host currentHost = hostWebAPI.getCurrentHost(request);
    User currentUser = (User) session.getAttribute(WebKeys.CMS_USER);

    String method = request.getMethod();
    String errorURL = request.getParameter("errorURL");
    errorURL = (!UtilMethods.isSet(errorURL) ? request.getHeader("referer") : errorURL);
    if (errorURL.indexOf("?") > -1) {
      errorURL = errorURL.substring(0, errorURL.lastIndexOf("?"));
    }
    String x = request.getRequestURI();
    if (request.getParameterMap().size() < 2) {

      return null;
    }

    // Checking for captcha
    boolean useCaptcha = Config.getBooleanProperty("FORCE_CAPTCHA", true);
    if (!useCaptcha) {
      useCaptcha = new Boolean(request.getParameter("useCaptcha")).booleanValue();
    }

    String captcha = request.getParameter("captcha");
    if (useCaptcha) {
      Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME);
      String captchaSession = captchaObj != null ? captchaObj.getAnswer() : null;

      if (captcha == null && Config.getBooleanProperty("FORCE_CAPTCHA", true)) {
        response
            .getWriter()
            .write(
                "Captcha is required to submit this form ( FORCE_CAPTCHA=true ).<br>To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false");
        return null;
      }

      if (!UtilMethods.isSet(captcha)
          || !UtilMethods.isSet(captchaSession)
          || !captcha.equals(captchaSession)) {
        errors.add(
            Globals.ERROR_KEY,
            new ActionMessage("message.contentlet.required", "Validation Image"));
        request.setAttribute(Globals.ERROR_KEY, errors);
        session.setAttribute(Globals.ERROR_KEY, errors);
        String queryString = request.getQueryString();
        String invalidCaptchaURL = request.getParameter("invalidCaptchaReturnUrl");
        if (!UtilMethods.isSet(invalidCaptchaURL)) {
          invalidCaptchaURL = errorURL;
        }
        ActionForward af = new ActionForward();
        af.setRedirect(true);
        if (UtilMethods.isSet(queryString)) {

          af.setPath(invalidCaptchaURL + "?" + queryString + "&error=Validation-Image");
        } else {
          af.setPath(invalidCaptchaURL + "?error=Validation-Image");
        }

        return af;
      }
    }

    Map<String, Object> parameters = null;
    if (request instanceof UploadServletRequest) {
      UploadServletRequest uploadReq = (UploadServletRequest) request;
      parameters = new HashMap<String, Object>(uploadReq.getParameterMap());
      for (Entry<String, Object> entry : parameters.entrySet()) {
        if (entry.getKey().toLowerCase().indexOf("file") > -1
            && !entry.getKey().equals("attachFiles")) {
          parameters.put(entry.getKey(), uploadReq.getFile(entry.getKey()));
        }
      }
    } else {
      parameters = new HashMap<String, Object>(request.getParameterMap());
    }

    Set<String> toValidate = new java.util.HashSet<String>(parameters.keySet());

    // Enhancing the ignored parameters not to be send in the email
    String ignoredParameters = (String) EmailFactory.getMapValue("ignore", parameters);
    if (ignoredParameters == null) {
      ignoredParameters = "";
    }
    ignoredParameters +=
        ":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:";
    parameters.put("ignore", ignoredParameters);

    // getting categories from inodes
    // getting parent category name and child categories name
    // and replacing the "categories" parameter
    String categories = "";
    String[] categoriesArray = request.getParameterValues("categories");
    if (categoriesArray != null) {
      HashMap hashCategories = new HashMap<String, String>();
      for (int i = 0; i < categoriesArray.length; i++) {
        Category node = (Category) InodeFactory.getInode(categoriesArray[i], Category.class);
        Category parent = (Category) InodeFactory.getParentOfClass(node, Category.class);
        String parentCategoryName = parent.getCategoryName();

        if (hashCategories.containsKey(parentCategoryName)) {
          String childCategoryName = (String) hashCategories.get(parentCategoryName);
          if (UtilMethods.isSet(childCategoryName)) {
            childCategoryName += ", ";
          }
          childCategoryName += node.getCategoryName();
          hashCategories.put(parentCategoryName, childCategoryName);
        } else {
          hashCategories.put(parentCategoryName, node.getCategoryName());
        }
      }

      Set<String> keySet = hashCategories.keySet();
      for (String stringKey : keySet) {

        if (UtilMethods.isSet(categories)) {
          categories += "; ";
        }
        categories += stringKey + " : " + (String) hashCategories.get(stringKey);
        parameters.put(stringKey, (String) hashCategories.get(stringKey));
      }
      parameters.remove("categories");
    }

    WebForm webForm = new WebForm();
    try {
      /*validation parameter should ignore the returnUrl and erroURL field in the spam check*/
      String[] removeParams = ignoredParameters.split(":");
      for (String param : removeParams) {
        toValidate.remove(param);
      }

      parameters.put("request", request);
      parameters.put("response", response);

      // Sending the email
      webForm =
          EmailFactory.sendParameterizedEmail(parameters, toValidate, currentHost, currentUser);

      webForm.setCategories(categories);

      if (UtilMethods.isSet(request.getParameter("createAccount"))
          && request.getParameter("createAccount").equals("true")) {
        // if we create account set to true we create a user account and add user comments.
        createAccount(webForm, request);
        try {
          String userInode = webForm.getUserInode();
          String customFields = webForm.getCustomFields();
          customFields += " User Inode = " + String.valueOf(userInode) + " | ";
          webForm.setCustomFields(customFields);
        } catch (Exception e) {

        }
      }

      if (UtilMethods.isSet(webForm.getFormType())) {
        HibernateUtil.saveOrUpdate(webForm);
      }

      if (request.getParameter("return") != null) {
        ActionForward af =
            new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("return")));
        af.setRedirect(true);
        return af;
      } else if (request.getParameter("returnUrl") != null) {
        ActionForward af =
            new ActionForward(
                SecurityUtils.stripReferer(request, request.getParameter("returnUrl")));
        af.setRedirect(true);
        return af;
      } else {
        return rMapping.findForward("thankYouPage");
      }

    } catch (DotRuntimeException e) {
      errors.add(Globals.ERROR_KEY, new ActionMessage("error.processing.your.email"));
      request.getSession().setAttribute(Globals.ERROR_KEY, errors);

      String queryString = request.getQueryString();

      if (queryString == null) {
        java.util.Enumeration<String> parameterNames = request.getParameterNames();
        queryString = "";
        String parameterName;
        for (; parameterNames.hasMoreElements(); ) {
          parameterName = parameterNames.nextElement();

          if (0 < queryString.length()) {
            queryString =
                queryString
                    + "&"
                    + parameterName
                    + "="
                    + UtilMethods.encodeURL(request.getParameter(parameterName));
          } else {
            queryString =
                parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName));
          }
        }
      }

      ActionForward af;
      if (UtilMethods.isSet(queryString)) {
        af = new ActionForward(SecurityUtils.stripReferer(request, errorURL + "?" + queryString));
      } else {
        af = new ActionForward(SecurityUtils.stripReferer(request, errorURL));
      }

      af.setRedirect(true);

      return af;
    }
  }
  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;
  }
  public static InputStream buildVelocity(
      Container container, Identifier identifier, boolean EDIT_MODE) {

    InputStream result;
    StringBuilder sb = new StringBuilder();

    boolean isDynamic = UtilMethods.isSet(container.getLuceneQuery());

    //  let's write this puppy out to our file
    sb.append("#set($SERVER_NAME =\"$host.getHostname()\" )");
    sb.append("#set($CONTAINER_IDENTIFIER_INODE = '").append(identifier.getInode()).append("')");
    sb.append("#set($CONTAINER_INODE = '").append(container.getInode()).append("')");
    sb.append("#set($CONTAINER_MAX_CONTENTLETS = ")
        .append(container.getMaxContentlets())
        .append(")");
    Structure st =
        (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class);
    sb.append("#set($CONTAINER_STRUCTURE_NAME = \"")
        .append((UtilMethods.isSet(st.getName()) ? st.getName() : ""))
        .append("\")");
    sb.append("#set($STATIC_CONTAINER = ")
        .append(!UtilMethods.isSet(container.getLuceneQuery()))
        .append(")");
    sb.append("#set($SORT_PAGE = \"").append(container.getSortContentletsBy()).append("\")");
    sb.append("#set($containerInode = '").append(container.getInode()).append("')");

    if (EDIT_MODE) {
      // Permissions to read/use the container in order to be able to add content to it and reorder
      // content
      sb.append("#set($USE_CONTAINER_PERMISSION = $USE_CONTAINER_PERMISSION")
          .append(identifier.getInode())
          .append(")");

      // Permissions to edit the container based on write permission ).append( access to the portlet
      sb.append("#set($EDIT_CONTAINER_PERMISSION = $EDIT_CONTAINER_PERMISSION")
          .append(identifier.getInode())
          .append(")");

      // Permissions over the structure to add new contents
      sb.append("#set($ADD_CONTENT_PERMISSION = $ADD_CONTENT_PERMISSION")
          .append(identifier.getInode())
          .append(")");
    }

    sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")");
    sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize")
        .append(identifier.getInode())
        .append(")");

    sb.append("#set($CONTAINER_NAME = \"")
        .append(UtilMethods.espaceForVelocity(container.getTitle()))
        .append("\")");
    sb.append("#set($CONTAINER_STRUCTURE_NAME = \"")
        .append(UtilMethods.espaceForVelocity(st.getName()))
        .append("\")");
    if (UtilMethods.isSet(container.getNotes()))
      sb.append("#set($CONTAINER_NOTES = \"")
          .append(UtilMethods.espaceForVelocity(container.getNotes()))
          .append("\")");
    else sb.append("#set($CONTAINER_NOTES = \"\")");

    /*
     * isDynamic means that the content list will be pulled from lucene.
     */
    if (isDynamic) {
      String luceneQuery = container.getLuceneQuery();
      sb.append("#set($CONTENTS_PER_PAGE = \"$CONTAINER_MAX_CONTENTLETS\")");
      sb.append("#if($request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_per_page\"))");
      sb.append("#set($CONTENTS_PER_PAGE = $request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_per_page\"))");
      sb.append("#end");
      sb.append("#set($CURRENT_PAGE = \"1\")");
      sb.append("#if($request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_page\"))");
      sb.append("#set($CURRENT_PAGE = $request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_page\"))");
      sb.append("#end");
      sb.append("#set($LUCENE_QUERY = \"").append(luceneQuery).append("\")");
    }

    // if the container needs to get its contentlets
    if (container.getMaxContentlets() > 0) {
      sb.append("#if($EDIT_MODE)");

      // To edit the look, see WEB-INF/velocity/static/preview/container_controls.vtl
      sb.append("<div class='dotContainer'>");
      sb.append("#end");

      // pre loop if it exists
      if (UtilMethods.isSet(container.getPreLoop())) {
        sb.append(container.getPreLoop());
      }

      // let's do the search of contentlets using lucene query
      if (isDynamic) {
        Structure containerStructure =
            (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class);

        sb.append("#set($contentletResultsMap")
            .append(identifier.getInode())
            .append(" = $contents.searchWithLuceneQuery(\"")
            .append(containerStructure.getInode())
            .append("\", ")
            .append("\"$LUCENE_QUERY\", ")
            .append("\"$SORT_PAGE\", ")
            .append("$CURRENT_PAGE, $CONTENTS_PER_PAGE)) ");
        sb.append("#set($contentletList")
            .append(identifier.getInode())
            .append(" = $contents.getContentIdentifiersFromLuceneHits($contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"assets\")))");

        sb.append("#set($HAS_NEXT_PAGE = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"has_next_page\"))");
        sb.append("#set($HAS_PREVIOUS_PAGE = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"has_previous_page\"))");
        sb.append("#set($TOTAL_CONTENTS = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"total_records_int\"))");
        sb.append("#set($TOTAL_PAGES = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"total_pages_int\"))");
        sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")");
        sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize")
            .append(identifier.getInode())
            .append(")");
      }

      sb.append("#foreach ($contentletId in $contentletList")
          .append(identifier.getInode())
          .append(")");

      // ##Checking of contentlet is parseable and not throwing errors
      if (EDIT_MODE) {
        sb.append("#if($webapi.canParseContent($contentletId,true))");
      }
      // sb.append("\n#if($webapi.canParseContent($contentletId,"+EDIT_MODE+")) ");
      sb.append(" #set($_show_working_=false) ");
      // if timemachine future enabled
      sb.append(" #if($request.session.getAttribute(\"tm_date\")) ");
      sb.append(
          "  #set($_tmdate=$date.toDate($webapi.parseLong($request.session.getAttribute(\"tm_date\")))) ");
      sb.append("  #set($_ident=$webapi.findIdentifierById($contentletId)) ");

      // if the content has expired we rewrite the identifier so it isn't loaded
      sb.append(
          "  #if($UtilMethods.isSet($_ident.sysExpireDate) && $_tmdate.after($_ident.sysExpireDate))");
      sb.append("   #set($contentletId='') ");
      sb.append("  #end ");

      // if the content should be published then force to show the working version
      sb.append(
          "  #if($UtilMethods.isSet($_ident.sysPublishDate) && $_tmdate.after($_ident.sysPublishDate))");
      sb.append("   #set($_show_working_=true) ");
      sb.append("  #end ");

      sb.append(" #end ");

      sb.append("#set($CONTENT_INODE = '')");
      sb.append(" #if($contentletId != '') ");
      sb.append("  #getContentDetail($contentletId) ");
      sb.append(" #end ");
      sb.append("#if($CONTENT_INODE != '')");

      if (!EDIT_MODE) {
        sb.append(
            "#set($_hasPermissionToViewContent = $contents.doesUserHasPermission($CONTENT_INODE, 1, $user, true))");
        // ##Checking permission to see content
        sb.append("#if($_hasPermissionToViewContent)");
      }

      String code = container.getCode();

      // ### HEADER ###
      String startTag = "${contentletStart}";
      if (!code.contains(startTag)) {
        sb.append("#if($EDIT_MODE)");
        sb.append("<div class=\"dotContentlet\">");
        // An empty div is added here because in Internet Explorer, there is a styling issue
        // http://jira.dotmarketing.net/browse/DOTCMS-1974
        sb.append("<div>");
        sb.append(" #end ");
      } else {
        String headerString =
            "#if($EDIT_MODE)" + "<div class=\"dotContentlet\">" + "<div>" + "#end ";
        code = code.replace(startTag, headerString);
      }
      // ### END HEADER ###

      // ### BODY ###
      String endTag = "${contentletEnd}";
      boolean containsEndTag = code.contains(endTag);
      if (containsEndTag) {
        String footerString =
            "#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)"
                + "$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')"
                + "#end"
                + "#if($EDIT_MODE)"
                + "<div class=\"dotClear\"></div></div>"
                + "#end ";
        code = code.replace(endTag, footerString);
      }

      sb.append("#if($isWidget == true)");
      sb.append("$widgetCode");
      sb.append(" #else");
      sb.append(code);
      sb.append(" #end ");
      // The empty div added for styling issue in Internet Explorer is closed here
      // http://jira.dotmarketing.net/browse/DOTCMS-1974
      sb.append("#if($EDIT_MODE)");
      sb.append("</div>");
      sb.append("#end ");
      // ### END BODY ###

      // ### FOOTER ###

      if (!containsEndTag) {
        sb.append("#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)");
        sb.append("#getContentDetail($contentletId)");
        sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')");
        sb.append("#end ");
        sb.append("#if($EDIT_MODE) ");
        sb.append("<div class=\"dotClear\"></div></div>");
        sb.append("#end ");
      }
      // ### END FOOTER ###

      if (!EDIT_MODE) {
        // ##End of checking permission to see content
        sb.append("#end ");
      }
      // ##Ends the inner canParse call
      sb.append("#end ");
      // ##Case the contentlet is not parseable and throwing errors
      if (EDIT_MODE) {
        sb.append("#else ");
        sb.append("#set($CONTENT_INODE =\"$webapi.getContentInode($contentletId)\")");
        sb.append(
            "#set($EDIT_CONTENT_PERMISSION =\"$webapi.getContentPermissions($contentletId)\")");
        sb.append("<div class=\"dotContentlet\">");
        sb.append("	Content Parse Error. Check your Content Code. ");
        sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')");
        sb.append("<div class=\"dotClear\"></div></div>");
        sb.append("#end ");
      }

      // ##End of foreach loop
      sb.append("#end ");

      // post loop if it exists

      if (UtilMethods.isSet(container.getPostLoop())) {
        sb.append(container.getPostLoop());
      }
      // close our container preview mode div
      sb.append("#if($EDIT_MODE)");
      sb.append("$velutil.mergeTemplate('static/preview_mode/container_controls.vtl')");
      sb.append("</div>");
      sb.append("#end ");

    } else {

      sb.append(container.getCode());
    }

    try {
      String folderPath = (!EDIT_MODE) ? "live" + File.separator : "working" + File.separator;
      String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
      if (velocityRootPath.startsWith("/WEB-INF")) {
        velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath);
      }
      velocityRootPath += File.separator;
      String filePath =
          folderPath
              + identifier.getInode()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION");

      if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) {
        java.io.BufferedOutputStream tmpOut =
            new java.io.BufferedOutputStream(
                new java.io.FileOutputStream(
                    new java.io.File(
                        ConfigUtils.getDynamicVelocityPath() + File.separator + filePath)));
        // Specify a proper character encoding
        OutputStreamWriter out =
            new OutputStreamWriter(tmpOut, UtilMethods.getCharsetConfiguration());
        out.write(sb.toString());
        out.flush();
        out.close();
        tmpOut.close();
      }
    } catch (Exception e) {
      Logger.error(ContentletServices.class, e.toString(), e);
    }

    try {
      result = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e1) {
      result = new ByteArrayInputStream(sb.toString().getBytes());
      Logger.error(ContainerServices.class, e1.getMessage(), e1);
    }
    return result;
  }
Exemple #20
0
public class TrustFactory {
  private static final String truststore_path =
      Config.getStringProperty("TRUSTSTORE_PATH", null); // cacerts.jks";
  private static final String truststore_password =
      Config.getStringProperty("TRUSTSTORE_PWD", null);
  private static final String keystore_path =
      Config.getStringProperty("KEYSTORE_PATH", null); // keystore.jks";
  private static final String keystore_password = Config.getStringProperty("KEYSTORE_PWD", null);

  public SSLContext getSSLContext() {
    TrustManager mytm[] = null;
    KeyManager mykm[] = null;

    try {
      if (UtilMethods.isSet(truststore_path) && UtilMethods.isSet(truststore_password)) {
        mytm =
            new TrustManager[] {
              new MyX509TrustManager(truststore_path, truststore_password.toCharArray())
            };
      }

      if (UtilMethods.isSet(keystore_path) && UtilMethods.isSet(keystore_password)) {
        mykm =
            new KeyManager[] {new MyX509KeyManager(keystore_path, keystore_password.toCharArray())};
      }
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      Logger.debug(this.getClass(), ex.getMessage(), ex);
    }

    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(mykm, mytm, null);
    } catch (java.security.GeneralSecurityException ex) {
      Logger.error(this.getClass(), ex.getMessage(), ex);
    }
    return ctx;
  }

  public HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {

      @Override
      public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
        return true;
      }
    };
  }

  static class MyX509TrustManager implements X509TrustManager {

    /*
     * The default PKIX X509TrustManager9.  We'll delegate
     * decisions to it, and fall back to the logic in this class if the
     * default X509TrustManager doesn't trust it.
     */
    X509TrustManager pkixTrustManager;

    MyX509TrustManager(String trustStore, char[] password) throws Exception {
      this(new File(trustStore), password);
    }

    MyX509TrustManager(File trustStore, char[] password) throws Exception {
      // create a "default" JSSE X509TrustManager.

      KeyStore ks = KeyStore.getInstance("JKS");

      ks.load(new FileInputStream(trustStore), password);

      TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
      tmf.init(ks);

      TrustManager tms[] = tmf.getTrustManagers();

      /*
       * Iterate over the returned trustmanagers, look
       * for an instance of X509TrustManager.  If found,
       * use that as our "default" trust manager.
       */
      for (int i = 0; i < tms.length; i++) {
        if (tms[i] instanceof X509TrustManager) {
          pkixTrustManager = (X509TrustManager) tms[i];
          return;
        }
      }

      /*
       * Find some other way to initialize, or else we have to fail the
       * constructor.
       */
      throw new Exception("Couldn't initialize");
    }

    /*
     * Delegate to the default trust manager.
     */
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
      try {
        pkixTrustManager.checkClientTrusted(chain, authType);
      } catch (CertificateException excep) {
        Logger.error(this.getClass(), excep.getMessage());
        Logger.debug(this.getClass(), excep.getMessage(), excep);
      }
    }

    /*
     * Delegate to the default trust manager.
     */
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
      try {
        pkixTrustManager.checkServerTrusted(chain, authType);
      } catch (CertificateException excep) {
        Logger.error(this.getClass(), excep.getMessage());
        Logger.debug(this.getClass(), excep.getMessage(), excep);
        throw excep;
      }
    }

    /*
     * Merely pass this through.
     */
    public X509Certificate[] getAcceptedIssuers() {
      return pkixTrustManager.getAcceptedIssuers();
    }
  }

  static class MyX509KeyManager implements X509KeyManager {

    /*
     * The default PKIX X509KeyManager.  We'll delegate
     * decisions to it, and fall back to the logic in this class if the
     * default X509KeyManager doesn't trust it.
     */
    X509KeyManager pkixKeyManager;

    MyX509KeyManager(String keyStore, char[] password) throws Exception {
      this(new File(keyStore), password);
    }

    MyX509KeyManager(File keyStore, char[] password) throws Exception {
      // create a "default" JSSE X509KeyManager.

      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), password);

      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
      kmf.init(ks, password);

      KeyManager kms[] = kmf.getKeyManagers();

      /*
       * Iterate over the returned keymanagers, look
       * for an instance of X509KeyManager.  If found,
       * use that as our "default" key manager.
       */
      for (int i = 0; i < kms.length; i++) {
        if (kms[i] instanceof X509KeyManager) {
          pkixKeyManager = (X509KeyManager) kms[i];
          return;
        }
      }

      /*
       * Find some other way to initialize, or else we have to fail the
       * constructor.
       */
      throw new Exception("Couldn't initialize");
    }

    public PrivateKey getPrivateKey(String arg0) {
      return pkixKeyManager.getPrivateKey(arg0);
    }

    public X509Certificate[] getCertificateChain(String arg0) {
      return pkixKeyManager.getCertificateChain(arg0);
    }

    public String[] getClientAliases(String arg0, Principal[] arg1) {
      return pkixKeyManager.getClientAliases(arg0, arg1);
    }

    public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
      return pkixKeyManager.chooseClientAlias(arg0, arg1, arg2);
    }

    public String[] getServerAliases(String arg0, Principal[] arg1) {
      return pkixKeyManager.getServerAliases(arg0, arg1);
    }

    public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
      return pkixKeyManager.chooseServerAlias(arg0, arg1, arg2);
    }
  }
}
Exemple #21
0
 /**
  * Return if the DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE property is activated or not
  *
  * @return boolean
  */
 public static boolean canDefaultContentToDefaultLanguage() {
   boolean defaultContentToDefaultLanguage = false;
   defaultContentToDefaultLanguage =
       Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE");
   return defaultContentToDefaultLanguage;
 }
  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;
  }
  private void createAccount(WebForm form, HttpServletRequest request) throws Exception {

    User user =
        APILocator.getUserAPI()
            .loadByUserByEmail(form.getEmail(), APILocator.getUserAPI().getSystemUser(), false);
    User defaultUser = APILocator.getUserAPI().getDefaultUser();
    Date today = new Date();

    if (user.isNew() || (!user.isNew() && user.getLastLoginDate() == null)) {

      // ### CREATE USER ###
      Company company = PublicCompanyFactory.getDefaultCompany();
      user.setEmailAddress(form.getEmail().trim().toLowerCase());
      user.setFirstName(form.getFirstName() == null ? "" : form.getFirstName());
      user.setMiddleName(form.getMiddleName() == null ? "" : form.getMiddleName());
      user.setLastName(form.getLastName() == null ? "" : form.getLastName());
      user.setNickName("");
      user.setCompanyId(company.getCompanyId());
      user.setPasswordEncrypted(true);
      user.setGreeting("Welcome, " + user.getFullName() + "!");

      // Set defaults values
      if (user.isNew()) {
        // if it's a new user we set random password
        String pass = PublicEncryptionFactory.getRandomPassword();
        user.setPassword(PublicEncryptionFactory.digestString(pass));
        user.setLanguageId(defaultUser.getLanguageId());
        user.setTimeZoneId(defaultUser.getTimeZoneId());
        user.setSkinId(defaultUser.getSkinId());
        user.setDottedSkins(defaultUser.isDottedSkins());
        user.setRoundedSkins(defaultUser.isRoundedSkins());
        user.setResolution(defaultUser.getResolution());
        user.setRefreshRate(defaultUser.getRefreshRate());
        user.setLayoutIds("");
        user.setActive(true);
        user.setCreateDate(today);
      }
      APILocator.getUserAPI().save(user, APILocator.getUserAPI().getSystemUser(), false);
      // ### END CREATE USER ###

      // ### CREATE USER_PROXY ###
      UserProxy userProxy =
          com.dotmarketing.business.APILocator.getUserProxyAPI()
              .getUserProxy(user.getUserId(), APILocator.getUserAPI().getSystemUser(), false);
      userProxy.setPrefix("");
      userProxy.setTitle(form.getTitle());
      userProxy.setOrganization(form.getOrganization());
      userProxy.setUserId(user.getUserId());
      com.dotmarketing.business.APILocator.getUserProxyAPI()
          .saveUserProxy(userProxy, APILocator.getUserAPI().getSystemUser(), false);
      // ### END CRETE USER_PROXY ###

      // saving user inode on web form
      form.setUserInode(userProxy.getInode());
      if (UtilMethods.isSet(form.getFormType())) {
        HibernateUtil.saveOrUpdate(form);
      }

      ///// WE CAN DO THIS! BUT WE NEED TO ADD CATEGORIES TO WEBFORM AND ALSO CHANGE THE PROCESSES
      // THAT
      //// CREATE THE EXCEL DOWNLOAD FROM WEB FORMS. I DIDN'T ADD IT SO I COMMENTED THIS CODE FOR
      // NOW
      // get the old categories, wipe them out
      /*
      List<Category> categories = InodeFactory.getParentsOfClass(userProxy, Category.class);
      for (int i = 0; i < categories.size(); i++) {
      	categories.get(i).deleteChild(userProxy);
      }
       */
      // Save the new categories
      /*String[] arr = form.getCategories();
      if (arr != null) {
      	for (int i = 0; i < arr.length; i++) {
      		Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
      		node.addChild(userProxy);
      	}
      }*/

      // ### CREATE ADDRESS ###
      try {
        List<Address> addresses = PublicAddressFactory.getAddressesByUserId(user.getUserId());
        Address address =
            (addresses.size() > 0 ? addresses.get(0) : PublicAddressFactory.getInstance());
        address.setStreet1(form.getAddress1() == null ? "" : form.getAddress1());
        address.setStreet2(form.getAddress2() == null ? "" : form.getAddress2());
        address.setCity(form.getCity() == null ? "" : form.getCity());
        address.setState(form.getState() == null ? "" : form.getState());
        address.setZip(form.getZip() == null ? "" : form.getZip());
        String phone = form.getPhone();
        address.setPhone(phone == null ? "" : phone);
        address.setUserId(user.getUserId());
        address.setCompanyId(company.getCompanyId());
        PublicAddressFactory.save(address);
      } catch (Exception ex) {
        Logger.error(this, ex.getMessage(), ex);
      }

      Role defaultRole =
          com.dotmarketing.business.APILocator.getRoleAPI()
              .loadRoleByKey(Config.getStringProperty("CMS_VIEWER_ROLE"));
      String roleId = defaultRole.getId();
      if (InodeUtils.isSet(roleId)) {
        com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user);
      }
    }
    // ### END CREATE ADDRESS ###

    // ### BUILD THE USER COMMENT ###
    addUserComments(user.getUserId(), form, request);
    // ### END BUILD THE USER COMMENT ###

    /* associate user with their clickstream request */
    if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) {
      ClickstreamFactory.setClickStreamUser(user.getUserId(), request);
    }
  }
Exemple #24
0
  public static void copyFile(File source, File destination, boolean hardLinks) {
    if (!source.exists()) {
      return;
    }

    if (hardLinks && !Config.getBooleanProperty("CONTENT_VERSION_HARD_LINK", true)) {
      hardLinks = false;
    }

    if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) {

      destination.getParentFile().mkdirs();
    }

    if (hardLinks) {
      // I think we need to be sure to unlink first
      if (destination.exists()) {
        Path destinationPath = Paths.get(destination.getAbsolutePath());
        try {
          // "If the file is a symbolic link then the symbolic link itself, not the final target of
          // the link, is deleted."
          Files.delete(destinationPath);
        } catch (IOException e) {
          Logger.error(
              FileUtil.class, "Error removing hardLink: " + destination.getAbsolutePath(), e);
        }
      }

      try {

        Path newLink = Paths.get(destination.getAbsolutePath());
        Path existingFile = Paths.get(source.getAbsolutePath());

        Files.createLink(newLink, existingFile);
        // setting this means we will try again if we cannot hard link
        if (!destination.exists()) {
          hardLinks = false;
        }
      } catch (IOException e) {
        Logger.error(
            FileUtil.class,
            "Can't create hardLink. source: "
                + source.getAbsolutePath()
                + ", destination: "
                + destination.getAbsolutePath());
        // setting this means we will try again if we cannot hard link
        hardLinks = false;
      }
    }
    if (!hardLinks) {

      FileChannel srcChannel = null;
      FileChannel dstChannel = null;

      try {
        srcChannel = new FileInputStream(source).getChannel();
        dstChannel = new FileOutputStream(destination).getChannel();

        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
      } catch (IOException ioe) {
        Logger.error(FileUtil.class, ioe.getMessage(), ioe);
      } finally {
        try {
          srcChannel.close();
          dstChannel.close();
        } catch (IOException ioe) {
          Logger.error(FileUtil.class, ioe.getMessage(), ioe);
        }
      }
    }
  }
Exemple #25
0
  @SuppressWarnings("unchecked")
  public static InputStream buildStream(HTMLPage htmlPage, Identifier identifier, boolean EDIT_MODE)
      throws DotDataException, DotSecurityException {
    String folderPath = (!EDIT_MODE) ? "live/" : "working/";
    InputStream result;
    StringBuilder sb = new StringBuilder();

    ContentletAPI conAPI = APILocator.getContentletAPI();
    Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, EDIT_MODE);
    if (cmsTemplate == null || !InodeUtils.isSet(cmsTemplate.getInode())) {
      Logger.error(
          This.class,
          "PAGE DOES NOT HAVE A VALID TEMPLATE (template unpublished?) : page id "
              + htmlPage.getIdentifier()
              + ":"
              + identifier.getURI());
    }

    // gets pageChannel for this path
    java.util.StringTokenizer st =
        new java.util.StringTokenizer(String.valueOf(identifier.getURI()), "/");
    String pageChannel = null;
    if (st.hasMoreTokens()) {
      pageChannel = st.nextToken();
    }

    // set the page cache var
    if (htmlPage.getCacheTTL() > 0 && LicenseUtil.getLevel() > 99) {
      sb.append("#set($dotPageCacheDate = \"").append(new java.util.Date()).append("\")");
      sb.append("#set($dotPageCacheTTL = \"").append(htmlPage.getCacheTTL()).append("\")");
    }

    // set the host variables
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();

    Host host = htmlPageAPI.getParentHost(htmlPage);
    sb.append("#if(!$doNotParseTemplate)");
    sb.append("$velutil.mergeTemplate('")
        .append(folderPath)
        .append(host.getIdentifier())
        .append(".")
        .append(Config.getStringProperty("VELOCITY_HOST_EXTENSION"))
        .append("')");
    sb.append(" #end ");

    // creates the context where to place the variables
    // Build a context to pass to the page
    sb.append("#if(!$doNotSetPageInfo)");
    sb.append("#set ( $quote = '\"' )");
    sb.append("#set ($HTMLPAGE_INODE = \"")
        .append(String.valueOf(htmlPage.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_IDENTIFIER = \"")
        .append(String.valueOf(htmlPage.getIdentifier()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_TITLE = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append(
            "#set ($HTMLPAGE_FRIENDLY_NAME = \""
                + UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");
    sb.append("#set ($TEMPLATE_INODE = \"")
        .append(String.valueOf(cmsTemplate.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getMetadata()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"#fixBreaks($HTMLPAGE_META)\")");

    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoDescription()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"#fixBreaks($HTMLPAGE_DESCRIPTION)\")");

    sb.append("#set ($HTMLPAGE_KEYWORDS = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoKeywords()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_KEYWORDS = \"#fixBreaks($HTMLPAGE_KEYWORDS)\")");

    sb.append("#set ($HTMLPAGE_SECURE = \"")
        .append(String.valueOf(htmlPage.isHttpsRequired()))
        .append("\" )");
    sb.append("#set ($VTLSERVLET_URI = \"")
        .append(UtilMethods.encodeURIComponent(identifier.getURI()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_REDIRECT = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getRedirect()))
        .append("\" )");

    sb.append("#set ($pageTitle = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append("#set ($pageChannel = \"").append(pageChannel).append("\" )");
    sb.append("#set ($friendlyName = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");

    Date moddate = null;
    if (UtilMethods.isSet(htmlPage.getModDate())) {
      moddate = htmlPage.getModDate();
    } else {
      moddate = htmlPage.getStartDate();
    }

    moddate = new Timestamp(moddate.getTime());

    sb.append("#set ($HTML_PAGE_LAST_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append("#set ($HTMLPAGE_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append(" #end ");

    // get the containers for the page and stick them in context
    // List identifiers = InodeFactory.getChildrenClass(cmsTemplate, Identifier.class);

    List<Container> containerList =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);

    Iterator i = containerList.iterator();
    while (i.hasNext()) {
      Container ident = (Container) i.next();

      Container c = null;
      if (EDIT_MODE) {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findWorkingVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      } else {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findLiveVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      }
      // sets container to load the container file
      sb.append("#set ($container")
          .append(ident.getIdentifier())
          .append(" = \"")
          .append(folderPath)
          .append(ident.getIdentifier())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"))
          .append("\" )");

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean dynamicContainer = UtilMethods.isSet(c.getLuceneQuery());

      int langCounter = 0;

      List<Contentlet> contentlets = new ArrayList<Contentlet>();
      List<Contentlet> contentletsFull = new ArrayList<Contentlet>();
      if (!dynamicContainer) {
        Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
        Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
        // The container doesn't have categories
        try {
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getId(),
                  idenContainer.getId(),
                  sort,
                  EDIT_MODE,
                  -1,
                  APILocator.getUserAPI().getSystemUser(),
                  false);
          if (EDIT_MODE) contentletsFull = contentlets;
          else
            contentletsFull =
                conAPI.findPageContentlets(
                    idenHtmlPage.getId(),
                    idenContainer.getId(),
                    sort,
                    true,
                    -1,
                    APILocator.getUserAPI().getSystemUser(),
                    false);
        } catch (Exception e) {
          Logger.error(PageServices.class, "Unable to retrive contentlets on page", e);
        }
        Logger.debug(
            PageServices.class,
            "HTMLPage= "
                + htmlPage.getInode()
                + " Container="
                + c.getInode()
                + " Language=-1 Contentlets="
                + contentlets.size());
      }
      // this is to filter the contentlets list removing the repited identifiers
      if (contentlets.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentlets) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentlets = contentletsFilter;
      }
      if (contentletsFull.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentletsFull) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentletsFull = contentletsFilter;
      }

      StringBuilder widgetpree = new StringBuilder();
      StringBuilder widgetpreeFull = new StringBuilder();

      StringBuilder contentletList = new StringBuilder();
      int count = 0;
      for (Contentlet contentlet : contentlets) {
        contentletList
            .append(count == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpree.append(field.getValues().trim());
        }
        if (++count >= c.getMaxContentlets()) break;
      }

      StringBuilder contentletListFull = new StringBuilder();
      int countFull = 0;
      for (Contentlet contentlet : contentletsFull) {
        contentletListFull
            .append(countFull == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpreeFull.append(field.getValues().trim());
        }
        if (++countFull >= c.getMaxContentlets()) break;
      }

      sb.append("#if($request.session.getAttribute(\"tm_date\"))");
      sb.append(widgetpreeFull);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletListFull.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(countFull)
          .append(")");
      sb.append("#else ");
      sb.append(widgetpree);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletList.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(count)
          .append(")");
      sb.append("#end ");
      langCounter++;
    }

    if (htmlPage.isHttpsRequired()) {
      sb.append(" #if(!$ADMIN_MODE  && !$request.isSecure())");
      sb.append("    #if($request.getQueryString())");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')?$request.getQueryString()\")");
      sb.append("    #else ");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')\")");
      sb.append("    #end ");
      sb.append("    $response.sendRedirect(\"$REDIRECT_URL\")");
      sb.append(" #end ");
    }

    sb.append("#if($HTMLPAGE_REDIRECT != \"\")");
    sb.append("    $response.sendRedirect(\"$HTMLPAGE_REDIRECT\")");
    sb.append("#end");

    Identifier iden = APILocator.getIdentifierAPI().find(cmsTemplate);

    sb.append("#if(!$doNotParseTemplate)");
    if (cmsTemplate.isDrawed()) { // We have a designed template
      // Setting some theme variables
      sb.append("#set ($dotTheme = $templatetool.theme(\"")
          .append(cmsTemplate.getTheme())
          .append("\",\"")
          .append(host.getIdentifier())
          .append("\"))");
      sb.append("#set ($dotThemeLayout = $templatetool.themeLayout(\"")
          .append(cmsTemplate.getInode())
          .append("\" ))");
      // Merging our template
      sb.append("$velutil.mergeTemplate(\"$dotTheme.templatePath\")");
    } else {
      sb.append("$velutil.mergeTemplate('")
          .append(folderPath)
          .append(iden.getInode())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"))
          .append("')");
    }
    sb.append("#end");

    try {

      if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) {
        String realFolderPath =
            (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator;
        String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
        String filePath =
            realFolderPath
                + identifier.getInode()
                + "."
                + Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION");
        if (velocityRootPath.startsWith("/WEB-INF")) {
          velocityRootPath = com.liferay.util.FileUtil.getRealPath(velocityRootPath);
        }
        velocityRootPath += java.io.File.separator;

        java.io.BufferedOutputStream tmpOut =
            new java.io.BufferedOutputStream(
                new java.io.FileOutputStream(
                    new java.io.File(
                        ConfigUtils.getDynamicVelocityPath() + java.io.File.separator + filePath)));
        // Specify a proper character encoding
        OutputStreamWriter out =
            new OutputStreamWriter(tmpOut, UtilMethods.getCharsetConfiguration());

        out.write(sb.toString());

        out.flush();
        out.close();
        tmpOut.close();
      }
    } catch (Exception e) {
      Logger.error(PageServices.class, e.toString(), e);
    }
    try {
      result = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e1) {
      result = new ByteArrayInputStream(sb.toString().getBytes());
      Logger.error(ContainerServices.class, e1.getMessage(), e1);
    }
    return result;
  }
  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");
    }
  }
Exemple #27
0
 public static void copyFile(File source, File destination) {
   copyFile(source, destination, Config.getBooleanProperty("CONTENT_VERSION_HARD_LINK", true));
 }
  @SuppressWarnings("unchecked")
  public void doPreviewMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration());
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User user = null;
    HttpSession session = request.getSession(false);
    try {
      if (session != null)
        user =
            (com.liferay.portal.model.User)
                session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", id.getInode());
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage) APILocator.getVersionableAPI().findWorkingVersion(id, user, true);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user);
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
            htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, user, true);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, false, true, host);
    context.put("previewPage", "2");
    context.put("livePage", "0");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      context.put(
          "EDIT_CONTAINER_PERMISSION" + c.getIdentifier(),
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, true));

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);

      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, user, true);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      List<Contentlet> contentlets = null;

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, user, true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null && contentlets.size() > 0) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user, true);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }

        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), user.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {

      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
  protected void _loadStructures(
      RenderRequest req, User user, String countWebKey, String viewWebKey, String queryWebKey)
      throws Exception {

    com.liferay.portlet.RenderRequestImpl reqImpl = (com.liferay.portlet.RenderRequestImpl) req;
    HttpServletRequest httpReq = reqImpl.getHttpServletRequest();
    // gets the session object for the messages
    HttpSession session = httpReq.getSession();

    Integer structureType =
        (Integer) session.getAttribute(com.dotmarketing.util.WebKeys.Structure.STRUCTURE_EDIT_TYPE);
    if (req.getParameter("structureType") != null)
      structureType = Integer.parseInt(req.getParameter("structureType"));
    if (structureType != null)
      session.setAttribute(
          com.dotmarketing.util.WebKeys.Structure.STRUCTURE_EDIT_TYPE, structureType);

    String query = req.getParameter("query");
    String resetQuery = req.getParameter("resetQuery");

    List<Structure> structures = new java.util.ArrayList<Structure>();

    try {
      String orderby = req.getParameter("orderBy");
      if (!UtilMethods.isSet(orderby)) {
        orderby = "upper(name)";
      }
      String direction = req.getParameter("direction");
      if (!UtilMethods.isSet(direction)) {
        direction = "asc";
      }

      int pageNumber = 1;

      if (UtilMethods.isSet(req.getParameter("pageNumber"))) {
        pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
      }

      int limit = com.dotmarketing.util.Config.getIntProperty("PER_PAGE");

      int offset = (pageNumber - 1) * limit;

      if ((query == null) && (resetQuery == null)) {
        query = (String) session.getAttribute(queryWebKey);
      }
      session.setAttribute(queryWebKey, query);

      int count = 0;
      String queryCondition = "";

      if (((query != null) && (query.length() != 0)) || (structureType != null)) {

        if (query == null) query = "";
        query = query.trim();
        if (UtilMethods.isSet(query)) {
          queryCondition +=
              "(lower(name) "
                  + "like '%"
                  + query.toLowerCase().replace("\'", "\\\'")
                  + "%' or inode='"
                  + query
                  + "')";
        }

      } else {
        Logger.debug(this, "Getting all Forms Structures");
      }

      if (UtilMethods.isSet(queryCondition)) {
        queryCondition += " and structuretype=" + Structure.STRUCTURE_TYPE_FORM;
      } else {
        queryCondition += " structuretype=" + Structure.STRUCTURE_TYPE_FORM;
      }

      structures =
          StructureFactory.getStructuresByUser(
              user, queryCondition, orderby, limit, offset, direction);
      count = (int) ((PaginatedArrayList<Structure>) structures).getTotalResults();
      req.setAttribute(countWebKey, new Integer(count));
      req.setAttribute(viewWebKey, structures);
    } catch (Exception e) {
      req.setAttribute(viewWebKey, structures);
      Logger.error(this, "Exception e =" + e.getMessage(), e);
      throw new Exception(e.getMessage());
    }
  }
  @SuppressWarnings("unchecked")
  protected void doEditMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = request.getRequestURI();
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User backendUser = null;
    try {
      backendUser = com.liferay.portal.util.PortalUtil.getUser(request);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", String.valueOf(id.getInode()));
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasAddChildrenPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, backendUser);
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, backendUser);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser);
    context.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", new Boolean(hasAddChildrenPermOverHTMLPage));
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));
    context.put("canAddForm", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));
    context.put("canViewDiff", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
                htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser)
            && portletAPI.hasTemplateManagerRights(backendUser);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    if (cmsTemplate == null) { // DOTCMS-4051
      cmsTemplate = new com.dotmarketing.portlets.templates.model.Template();
      Logger.debug(VelocityServlet.class, "HTMLPAGE TEMPLATE NOT FOUND");
    }

    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, true, false, host);
    // added to show tabs
    context.put("previewPage", "1");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      boolean hasWritePermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, backendUser, false)
              && portletAPI.hasContainerManagerRights(backendUser);
      boolean hasReadPermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_READ, backendUser, false);
      context.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer);
      if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true);
      else
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer);

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);
      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, backendUser);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      List<Contentlet> contentlets = null;

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(),
                  idenContainer.getInode(),
                  sort,
                  true,
                  -1,
                  backendUser,
                  true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());

        } else {
          String luceneQuery = c.getLuceneQuery();
          int limit = c.getMaxContentlets();
          String sortBy = c.getSortContentletsBy();
          int offset = 0;
          contentlets = conAPI.search(luceneQuery, limit, offset, sortBy, backendUser, true);
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, backendUser);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }
        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
        // ### Add the structure fake contentlet ###
        if (contentletList.size() == 0) {
          Structure structure = ContainerFactory.getContainerStructure(c);
          contentletList.add(structure.getInode() + "");
          // sets contentletlist with all the files to load per
          // container
          context.remove("contentletList" + c.getIdentifier());
          context.remove("totalSize" + c.getIdentifier());
          // http://jira.dotmarketing.net/browse/DOTCMS-2876
          context.put("contentletList" + c.getIdentifier(), new long[0]);
          context.put("totalSize" + c.getIdentifier(), 0);
        }
        // ### END Add the structure fake contentlet ###

      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), backendUser.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      // Return a resource not found right away if the page is not found,
      // not try to load the frames
      if (!InodeUtils.isSet(templateIdentifier.getInode())) throw new ResourceNotFoundException("");
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {
      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }