Ejemplo n.º 1
0
  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);
    }
  }
Ejemplo n.º 2
0
 public CalendarAjax() {
   eventAPI = APILocator.getEventAPI();
   categoryAPI = APILocator.getCategoryAPI();
   contAPI = APILocator.getContentletAPI();
   userAPI = WebAPILocator.getUserWebAPI();
   perAPI = APILocator.getPermissionAPI();
 }
Ejemplo n.º 3
0
  public List<NavResult> getChildren() throws Exception {
    if (children == null && hostId != null && folderId != null) {
      // lazy loadinge children
      Host host = APILocator.getHostAPI().find(hostId, sysuser, true);
      Folder folder = APILocator.getFolderAPI().find(folderId, sysuser, true);
      Identifier ident = APILocator.getIdentifierAPI().find(folder);
      NavResult lazyMe = NavTool.getNav(host, ident.getPath());
      children = lazyMe.getChildren();
      childrenFolderIds = lazyMe.getChildrenFolderIds();
    }
    if (children != null) {
      ArrayList<NavResult> list = new ArrayList<NavResult>();
      for (NavResult nn : children) {
        if (nn.isFolder()) {
          // for folders we avoid returning the same instance
          // it could be changed elsewhere and we need it to
          // load its children lazily
          NavResult ff = new NavResult(folderId, nn.hostId, nn.folderId);
          ff.setTitle(nn.getTitle());
          ff.setHref(nn.getHref());
          ff.setOrder(nn.getOrder());
          ff.setType(nn.getType());
          ff.setPermissionId(nn.getPermissionId());
          list.add(ff);
        } else {
          list.add(nn);
        }
      }

      if (checkPermissions) {
        // now filtering permissions
        List<NavResult> allow = new ArrayList<NavResult>(list.size());
        Context ctx = (VelocityContext) VelocityServlet.velocityCtx.get();
        HttpServletRequest req = (HttpServletRequest) ctx.get("request");
        User currentUser = WebAPILocator.getUserWebAPI().getLoggedInUser(req);
        if (currentUser == null) currentUser = APILocator.getUserAPI().getAnonymousUser();
        for (NavResult nv : list) {
          try {
            if (APILocator.getPermissionAPI()
                .doesUserHavePermission(nv, PermissionAPI.PERMISSION_READ, currentUser)) {
              allow.add(nv);
            }
          } catch (Exception ex) {
            Logger.error(this, ex.getMessage(), ex);
          }
        }
        return allow;
      } else return list;
    } else {
      return new ArrayList<NavResult>();
    }
  }
 /**
  * Retrieve the current host from the request
  *
  * @return the current host
  * @throws RuntimeException an exception that wraps the actual dotCMS exception when the host
  *     can't be found
  */
 public static Host getCurrentHost(HttpServletRequest request) {
   try {
     return WebAPILocator.getHostWebAPI().getCurrentHost(request);
   } catch (PortalException e) {
     throw new RuntimeException(e);
   } catch (SystemException e) {
     throw new RuntimeException(e);
   } catch (DotDataException e) {
     throw new RuntimeException(e);
   } catch (DotSecurityException e) {
     throw new RuntimeException(e);
   }
 }
  public static ClickstreamRequest getClickstreamRequest(
      HttpServletRequest request, Date timestamp) {

    HttpSession session = request.getSession();
    long languageId = langAPI.getDefaultLanguage().getId();
    if (session.getAttribute(WebKeys.HTMLPAGE_LANGUAGE) != null) {
      languageId = Long.parseLong(session.getAttribute(WebKeys.HTMLPAGE_LANGUAGE).toString());
    }

    String uri = request.getRequestURI();
    if (request.getAttribute(WebKeys.CLICKSTREAM_URI_OVERRIDE) != null) {
      uri = (String) request.getAttribute(WebKeys.CLICKSTREAM_URI_OVERRIDE);
    }

    HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();
    Host host = null;

    try {
      host = hostWebAPI.getCurrentHost(request);
    } catch (PortalException e) {
      Logger.error(
          ClickstreamRequestFactory.class,
          "Unable to retrieve current request host for URI " + uri);
    } catch (SystemException e) {
      Logger.error(
          ClickstreamRequestFactory.class,
          "Unable to retrieve current request host for URI  " + uri);
    } catch (DotDataException e) {
      Logger.error(
          ClickstreamRequestFactory.class,
          "Unable to retrieve current request host for URI  " + uri);
    } catch (DotSecurityException e) {
      Logger.error(
          ClickstreamRequestFactory.class,
          "Unable to retrieve current request host for URI  " + uri);
    }

    String hostIdentifier = host.getIdentifier();

    ClickstreamRequest cr = new ClickstreamRequest();
    cr.setProtocol(request.getProtocol());
    cr.setServerName(request.getServerName());
    cr.setServerPort(request.getServerPort());
    cr.setQueryString(request.getQueryString());
    cr.setRemoteUser(request.getRemoteUser());
    cr.setRequestURI(uri);
    cr.setLanguageId(languageId);
    cr.setTimestamp(timestamp);
    cr.setHostId(hostIdentifier);
    return cr;
  }
/**
 * Workflow actionlet that call the link checker on the given content fields.
 *
 * @author Graziano Aliberti - Engineering Ingegneria Informatica
 * @author Jorge Urdaneta - dotCMS
 * @date Feb 28, 2012
 */
public class CheckURLAccessibilityActionlet extends WorkFlowActionlet {

  private static final long serialVersionUID = 5110097144813925204L;
  private static List<WorkflowActionletParameter> paramList = null;
  private UserWebAPI uWebAPI = WebAPILocator.getUserWebAPI();

  @Override
  public List<WorkflowActionletParameter> getParameters() {

    try {
      if (null == paramList) {
        paramList = new ArrayList<WorkflowActionletParameter>();
        paramList.add(
            new WorkflowActionletParameter(
                "fieldList",
                LanguageUtil.get(APILocator.getUserAPI().getSystemUser(), "checkURL.fieldList"),
                "",
                true));
      }
    } catch (Exception e) {
    }
    return paramList;
  }

  @Override
  public String getName() {
    return "Link Checker";
  }

  @Override
  public String getHowTo() {
    return "This actionlet check the links into the specified fields and reject the content with broken links";
  }

  @Override
  public void executeAction(
      WorkflowProcessor processor, Map<String, WorkflowActionClassParameter> params)
      throws WorkflowActionFailureException {
    if (LicenseUtil.getLevel() < 200) return; // the apis will do nothing anyway

    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();
    User user = null;
    try {
      user = uWebAPI.getLoggedInUser(request);
    } catch (Exception exx) {
      throw new WorkflowActionFailureException(exx.getMessage());
    }
    Contentlet con = processor.getContentlet();

    List<InvalidLink> httpResponse = null;
    try {
      httpResponse = APILocator.getLinkCheckerAPI().findInvalidLinks(con);
    } catch (Exception e1) {
      Logger.error(this, e1.getMessage(), e1);
      throw new WorkflowActionFailureException(e1.getMessage());
    }

    // if there are unreachable URL...
    if (httpResponse.size() > 0) {
      String msg = "";
      try {
        msg = LanguageUtil.get(user, "checkURL.errorBrokenLinks");
      } catch (Exception e) {

      }
      throw new WorkflowActionFailureException(
          LinkCheckerUtil.buildPopupMsgWithLinksList(msg, httpResponse));
    }
  }
}
Ejemplo n.º 7
0
 public TemplateAjax() {
   templateAPI = APILocator.getTemplateAPI();
   userWebAPI = WebAPILocator.getUserWebAPI();
   hostAPI = APILocator.getHostAPI();
 }
Ejemplo n.º 8
0
public abstract class VelocityServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private ContentletAPI conAPI = APILocator.getContentletAPI();

  private static PortletURLUtil portletURLUtil = new PortletURLUtil();

  private static UtilMethods utilMethods = new UtilMethods();

  private static InodeUtils inodeUtils = new InodeUtils();

  private static PermissionAPI permissionAPI = APILocator.getPermissionAPI();

  private static PortletAPI portletAPI = APILocator.getPortletAPI();

  private static LanguageAPI langAPI = APILocator.getLanguageAPI();

  private static HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();

  /** @param permissionAPI the permissionAPI to set */
  public static void setPermissionAPI(PermissionAPI permissionAPIRef) {
    permissionAPI = permissionAPIRef;
  }

  private String CHARSET = null;

  private String VELOCITY_HTMLPAGE_EXTENSION = null;

  public static final String VELOCITY_CONTEXT = "velocityContext";

  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");
    }
  }

  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");
  }

  protected void doAdminMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    // LIVE MODE - LIVE PAGE

    com.liferay.portal.model.User backendUser = null;
    backendUser = com.liferay.portal.util.PortalUtil.getUser(request);

    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

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

    Host host = hostWebAPI.getCurrentHost(request);

    Identifier id = APILocator.getIdentifierAPI().find(host, uri);
    request.setAttribute("idInode", id.getInode());

    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    VelocityUtil.makeBackendContext(
        context, htmlPage, "", id.getURI(), request, true, false, false, host);

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

    Template template = null;

    if (request.getParameter("leftMenu") != null) {
      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      template =
          VelocityUtil.getEngine()
              .getTemplate("/live/" + id.getInode() + "." + VELOCITY_HTMLPAGE_EXTENSION);
    } else {
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    Logger.debug(VelocityServlet.class, "Got the template!!!!" + id.getInode());

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

      template.merge(context, out);

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

  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();
    }
  }

  @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());
    }
  }

  @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());
    }
  }

  // EACH CLIENT MAY HAVE ITS OWN VARIABLES
  // WE HAVE THE CLASS CLIENT THAT WILL IMPLEMENT THIS METHOD AND WILL BE ON
  // THE WEB.XML FILE
  protected abstract void _setClientVariablesOnContext(
      HttpServletRequest request, ChainedContext context);

  private boolean isArchive(HttpServletRequest request)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    String uri = request.getRequestURI();
    uri = UtilMethods.cleanURI(uri);

    Host host = null;
    String hostId = "";

    /*
     * String pageHostId = request.getParameter("host_id"); if (pageHostId
     * != null) { try { hostId = Long.parseLong(pageHostId); } catch
     * (Exception ex) { } }
     */
    hostId = request.getParameter("host_id");
    if (!InodeUtils.isSet(hostId)) {
      host = hostWebAPI.getCurrentHost(request);
      hostId = host.getIdentifier();
    } else {
      User user =
          (com.liferay.portal.model.User)
              request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
      host = hostWebAPI.find(hostId, user, true);
    }

    // Getting the identifier from the uri
    Identifier id = APILocator.getIdentifierAPI().find(host, uri);

    request.setAttribute("idInode", String.valueOf(id.getInode()));
    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);

    boolean isArchived = htmlPage.isDeleted();
    return isArchived;
  }

  /**
   * @author will this filter class strips all leading whitespace from the server response which is
   *     helpful for xml feeds and the like.
   */
  public class VelocityFilterWriter extends FilterWriter {

    private boolean firstNonWhiteSpace = false;

    public VelocityFilterWriter(Writer arg0) {
      super(arg0);
    }

    @Override
    public void write(char[] arg0) throws IOException {
      if (firstNonWhiteSpace) {
        super.write(arg0);
      } else {

        for (int i = 0; i < arg0.length; i++) {
          if (arg0[i] > 32) {
            firstNonWhiteSpace = true;
          }
          if (firstNonWhiteSpace) {
            super.write(arg0[i]);
          }
        }
      }
    }

    @Override
    public void write(String arg0) throws IOException {
      if (firstNonWhiteSpace) {
        super.write(arg0);
      } else {
        char[] stringChar = arg0.toCharArray();
        for (int i = 0; i < stringChar.length; i++) {

          if (stringChar[i] > 32) {
            firstNonWhiteSpace = true;
            super.write(arg0.substring(i, stringChar.length));
            break;
          }
        }
      }
    }
  }

  /**
   * This method trys to build a cache key based on the information given in the request - if the
   * page can't be cached, or caching is not availbale then return null
   *
   * @param request
   * @return
   */
  private String getPageCacheKey(HttpServletRequest request) {
    // no license
    if (LicenseUtil.getLevel() < 100) {
      return null;
    }
    // don't cache posts
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
      return null;
    }
    // nocache passed either as a session var, as a request var or as a
    // request attribute
    if ("no".equals(request.getParameter("dotcache"))
        || "no".equals(request.getAttribute("dotcache"))
        || "no".equals(request.getSession().getAttribute("dotcache"))) {
      return null;
    }

    String idInode = (String) request.getAttribute("idInode");

    User user =
        (com.liferay.portal.model.User)
            request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);

    HTMLPage page = null;
    try {
      page = APILocator.getHTMLPageAPI().loadLivePageById(idInode, user, true);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return null;
    }
    if (page == null || page.getCacheTTL() < 1) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(page.getInode());
    sb.append("_" + page.getModDate().getTime());

    String userId = (user != null) ? user.getUserId() : "PUBLIC";
    sb.append("_" + userId);

    String language =
        (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE);
    sb.append("_" + language);

    String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE);
    if (urlMap != null) {
      sb.append("_" + urlMap);
    }

    if (UtilMethods.isSet(request.getQueryString())) {
      sb.append("_" + request.getQueryString());
    }

    return sb.toString();
  }
}
Ejemplo n.º 9
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL)
        && LicenseUtil.getLevel() < 299) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.ORACLE)
        && LicenseUtil.getLevel() < 399) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (!LicenseUtil.isASAllowed()) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    Long profileTime = null;
    if (Config.getBooleanProperty("VELOCITY_PROFILING", false)) {
      profileTime = Calendar.getInstance().getTimeInMillis();
    }
    try {

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

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

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

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

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

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

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

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

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

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

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

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

        doLiveMode(request, response);
      }

    } catch (ResourceNotFoundException rnfe) {

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

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

    } catch (MethodInvocationException mie) {
      Logger.error(this, "MethodInvocationException" + mie.toString(), mie);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println(
            "MethodInvocationException Error on template:"
                + request.getRequestURI()
                + request.getQueryString());
      }
    } catch (Exception e) {
      Logger.error(this, e.toString(), e);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println("Error on template:" + request.getRequestURI() + request.getQueryString());
      }
    } finally {
      // catchall
      // added finally because of
      // http://jira.dotmarketing.net/browse/DOTCMS-1334
      try {
        HibernateUtil.commitTransaction();
      } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
      }
      DbConnectionFactory.closeConnection();
    }
    if (profileTime != null) {
      profileTime = Calendar.getInstance().getTimeInMillis() - profileTime;
      VelocityProfiler.log(
          VelocityServlet.class,
          "VelocityPage time: " + request.getRequestURL() + " " + profileTime + " millis");
    }
  }
Ejemplo n.º 10
0
  public Map<String, Object> saveEvent(List<String> formData, boolean isAutoSave, boolean isCheckin)
      throws LanguageException, PortalException, SystemException, DotDataException,
          DotSecurityException, java.text.ParseException {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    contentletFormData.put("recurrenceDaysOfWeek", recurrenceDaysOfWeek);

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

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

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

    }
    Boolean cont = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    boolean savingRecurrence = false;
    callbackData.put("referer", referer);
    HibernateUtil.commitTransaction();
    if (UtilMethods.isSet(newInode) && !savingRecurrence) {
      if (!contAPI.isInodeIndexed(newInode)) {
        Logger.error(this, "Timed out while waiting for index to return");
      }
    }
    return callbackData;
  }
Ejemplo n.º 11
0
public class SiteSearchWebAPI implements ViewTool {

  private static HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();
  private static UserAPI userAPI = APILocator.getUserAPI();
  private static SiteSearchAPI siteSearchAPI = APILocator.getSiteSearchAPI();

  public void init(Object initData) {}

  /**
   * Performs a search on the site search index using the current host in the request Sample usage
   * from velocity:
   *
   * <pre>{@code
   * #set($searchresults = $sitesearch.search("dotcms",null,0,10,$request))
   * #set($hitsdetail = $searchresults.getDetails())
   * #set($summaries = $searchresults.getSummaries())
   * #foreach ($i in [0..$math.sub($searchresults.getEnd(),1)])
   *    $hitsdetail.get($i).getValue("title")
   *    $hitsdetail.get($i).getValue("url")
   *    $summaries.get($i).toHtml(true)
   * #end
   * }</pre>
   *
   * @param query String to search for
   * @param sort Property to sort the results
   * @param start Start row
   * @param rows Number of rows to return (10 by default)
   * @param request
   * @return DotSearchResults
   * @throws IOException
   */
  public DotSearchResults search(
      String query, String sort, int start, int rows, HttpServletRequest request)
      throws IOException {

    Host host = null;

    try {
      host = hostWebAPI.getCurrentHost(request);
    } catch (Exception e) {
      Logger.error(this, e.getMessage(), e);
      try {
        Logger.warn(this, "Error getting host from request, trying default host");
        host = hostWebAPI.findDefaultHost(userAPI.getSystemUser(), false);
      } catch (Exception e1) {
        Logger.error(this, e1.getMessage(), e1);
        throw new DotRuntimeException(e.getMessage(), e);
      }
    }

    Locale locale = (Locale) request.getSession().getAttribute(WebKeys.Globals_FRONTEND_LOCALE_KEY);
    String lang = request.getLocale().getLanguage();
    if (locale != null) {
      lang = locale.getLanguage();
    }

    DotSearchResults dsr =
        siteSearchAPI.search(query, sort, start, rows, lang, host.getIdentifier());

    dsr.setHost(host);
    dsr.setLang(lang);
    return dsr;
  }
}
Ejemplo n.º 12
0
/**
 * @author David
 * @version $Revision: 1.5 $ $Date: 2007/07/18 16:48:42 $
 */
public final class SubmitWebFormAction extends DispatchAction {

  HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();

  @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;
    }
  }

  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);
    }
  }

  private void addUserComments(String userid, WebForm webForm, HttpServletRequest request)
      throws Exception {

    Date now = new Date();
    String webFormType = webForm.getFormType();
    String webFormId = webForm.getWebFormId();

    UserComment userComments = new UserComment();
    userComments.setUserId(userid);
    userComments.setCommentUserId(userid);
    userComments.setDate(now);
    if (request.getParameter("comments") != null) {
      userComments.setComment(request.getParameter("comments"));
    } else if (UtilMethods.isSet(webForm.getFormType())) {
      userComments.setSubject("User submitted: " + webFormType);
      userComments.setComment("Web Form: " + webFormType + " - ID: " + webFormId);
    } else {
      userComments.setSubject("User submitted Form: Open Entry ");
      StringBuffer buffy = new StringBuffer();
      Enumeration x = request.getParameterNames();
      while (x.hasMoreElements()) {
        String key = (String) x.nextElement();
        buffy.append(key);
        buffy.append(":\t");
        buffy.append(request.getParameter(key));
        buffy.append("\n");
        if (buffy.length() > 65000) {
          break;
        }
      }
      userComments.setComment(buffy.toString());
    }

    userComments.setTypeComment(UserComment.TYPE_INCOMING);
    userComments.setMethod(UserComment.METHOD_WEB);
    userComments.setCommunicationId(null);
    UserCommentsFactory.saveUserComment(userComments);
  }
}