Пример #1
0
  public static String getForwardKey(PortletRequest portletRequest) {
    String portletId = (String) portletRequest.getAttribute(WebKeys.PORTLET_ID);

    String portletNamespace = PortalUtil.getPortletNamespace(portletId);

    return portletNamespace.concat(WebKeys.PORTLET_STRUTS_FORWARD);
  }
Пример #2
0
  public static String getPortletResourceNamespace(
      PortletRequest portletRequest, ThemeDisplay themeDisplay) throws Exception {

    String portletId = ParamUtil.getString(portletRequest, "portletResource");

    return PortalUtil.getPortletNamespace(portletId);
  }
  public LayoutTypePortletImpl(Layout layout) {
    super(layout);

    if (_nestedPortletsNamespace == null) {
      _nestedPortletsNamespace = PortalUtil.getPortletNamespace(PortletKeys.NESTED_PORTLETS);
    }

    _sourcePrototypeLayout = getSourcePrototypeLayout(layout);
  }
Пример #4
0
  public String getViewContentURL(String className, long classPK, ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    if (!themeDisplay.isSignedIn()
        || !isTrashEnabled(themeDisplay.getScopeGroupId())
        || !PortletPermissionUtil.hasControlPanelAccessPermission(
            themeDisplay.getPermissionChecker(),
            themeDisplay.getScopeGroupId(),
            PortletKeys.TRASH)) {

      return null;
    }

    TrashHandler trashHandler = TrashHandlerRegistryUtil.getTrashHandler(className);

    if (trashHandler.isInTrashContainer(classPK)) {
      ContainerModel containerModel = trashHandler.getTrashContainer(classPK);

      className = containerModel.getModelClassName();
      classPK = containerModel.getContainerModelId();

      trashHandler = TrashHandlerRegistryUtil.getTrashHandler(className);
    }

    TrashRenderer trashRenderer = trashHandler.getTrashRenderer(classPK);

    if (trashRenderer == null) {
      return null;
    }

    String namespace = PortalUtil.getPortletNamespace(PortletKeys.TRASH);

    Map<String, String[]> params = new HashMap<String, String[]>();

    params.put(namespace + "struts_action", new String[] {"/trash/view_content"});
    params.put(namespace + "redirect", new String[] {themeDisplay.getURLCurrent()});

    TrashEntry trashEntry = TrashEntryLocalServiceUtil.getEntry(className, classPK);

    if (trashEntry.getRootEntry() != null) {
      params.put(namespace + "className", new String[] {className});
      params.put(namespace + "classPK", new String[] {String.valueOf(classPK)});
    } else {
      params.put(
          namespace + "trashEntryId", new String[] {String.valueOf(trashEntry.getEntryId())});
    }

    params.put(namespace + "type", new String[] {trashRenderer.getType()});
    params.put(namespace + "showActions", new String[] {Boolean.FALSE.toString()});
    params.put(namespace + "showAssetMetadata", new String[] {Boolean.TRUE.toString()});
    params.put(namespace + "showEditURL", new String[] {Boolean.FALSE.toString()});

    return PortalUtil.getControlPanelFullURL(
        themeDisplay.getScopeGroupId(), PortletKeys.TRASH, params);
  }
  protected void onRemoveFromLayout(String portletId) throws SystemException {
    Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

    if (portlet == null) {
      return;
    }

    if (portlet.getRootPortletId().equals(PortletKeys.NESTED_PORTLETS)) {
      String portletNamespace = PortalUtil.getPortletNamespace(portletId);

      UnicodeProperties typeSettingsProperties = getTypeSettingsProperties();

      for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

        String key = entry.getKey();

        if (key.startsWith(portletNamespace)) {
          String portletIds = entry.getValue();

          String[] portletIdsArray = StringUtil.split(portletIds);

          for (String curPortletId : portletIdsArray) {
            onRemoveFromLayout(curPortletId);
          }
        }
      }

      removeNestedColumns(portletNamespace);
    }

    if (_enablePortletLayoutListener) {
      PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

      if ((portletLayoutListener != null)) {
        portletLayoutListener.onRemoveFromLayout(portletId, getPlid());
      }
    }

    deletePortletSetup(portletId);
  }
  public void populateParams(
      String friendlyURLPath,
      Map<String, String[]> parameterMap,
      Map<String, Object> requestContext) {

    int pos1 = friendlyURLPath.indexOf("/", 1);
    int pos2 = friendlyURLPath.indexOf("/", pos1 + 1);
    int pos3 = friendlyURLPath.indexOf("/", pos2 + 1);
    int pos4 = friendlyURLPath.indexOf("/", pos3 + 1);
    int pos5 = friendlyURLPath.indexOf("/", pos4 + 1);

    String portletId = friendlyURLPath.substring(pos1 + 1, pos2);

    addParameter(parameterMap, "p_p_id", portletId);
    addParameter(parameterMap, "p_p_state", friendlyURLPath.substring(pos2 + 1, pos3));
    addParameter(parameterMap, "p_p_mode", friendlyURLPath.substring(pos3 + 1, pos4));
    addParameter(parameterMap, "p_p_cacheability", friendlyURLPath.substring(pos4 + 1, pos5));

    String name = PortalUtil.getPortletNamespace(portletId) + "wsrp-navigationalState";

    addParameter(parameterMap, name, friendlyURLPath.substring(pos5 + 1));
  }
  protected void onRemoveFromLayout(String[] portletIds) {
    Set<String> portletIdList = new HashSet<>();

    for (String portletId : portletIds) {
      removeModesPortletId(portletId);
      removeStatesPortletId(portletId);

      portletIdList.add(portletId);

      String rootPortletId = PortletConstants.getRootPortletId(portletId);

      if (rootPortletId.equals(PortletKeys.NESTED_PORTLETS)) {
        String portletNamespace = PortalUtil.getPortletNamespace(portletId);

        UnicodeProperties typeSettingsProperties = getTypeSettingsProperties();

        for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

          String key = entry.getKey();

          if (!key.startsWith(portletNamespace)) {
            continue;
          }

          String nestedPortletIds = entry.getValue();

          for (String nestedPortletId : StringUtil.split(nestedPortletIds)) {

            removeModesPortletId(nestedPortletId);
            removeStatesPortletId(nestedPortletId);

            portletIdList.add(nestedPortletId);
          }
        }

        removeNestedColumns(portletNamespace);
      }

      Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId);

      if (portlet == null) {
        continue;
      }

      PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

      if (portletLayoutListener == null) {
        continue;
      }

      portletLayoutListener.updatePropertiesOnRemoveFromLayout(
          portletId, getTypeSettingsProperties());
    }

    try {
      PortletLocalServiceUtil.deletePortlets(
          getCompanyId(), portletIdList.toArray(new String[portletIdList.size()]), getPlid());
    } catch (PortalException pe) {
      _log.error(pe, pe);
    }
  }
Пример #8
0
  public static String getRefreshURL(HttpServletRequest request, ThemeDisplay themeDisplay) {

    StringBundler sb = new StringBundler(32);

    sb.append(themeDisplay.getPathMain());
    sb.append("/portal/render_portlet?p_l_id=");

    long plid = themeDisplay.getPlid();

    sb.append(plid);

    Portlet portlet = (Portlet) request.getAttribute(WebKeys.RENDER_PORTLET);

    String portletId = portlet.getPortletId();

    sb.append("&p_p_id=");
    sb.append(portletId);

    sb.append("&p_p_lifecycle=0&p_t_lifecycle=");
    sb.append(themeDisplay.getLifecycle());

    WindowState windowState = WindowState.NORMAL;

    if (themeDisplay.isStatePopUp()) {
      windowState = LiferayWindowState.POP_UP;
    } else {
      LayoutTypePortlet layoutTypePortlet = themeDisplay.getLayoutTypePortlet();

      if (layoutTypePortlet.hasStateMaxPortletId(portletId)) {
        windowState = WindowState.MAXIMIZED;
      } else if (layoutTypePortlet.hasStateMinPortletId(portletId)) {
        windowState = WindowState.MINIMIZED;
      }
    }

    sb.append("&p_p_state=");
    sb.append(windowState);

    sb.append("&p_p_mode=view&p_p_col_id=");

    String columnId = (String) request.getAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID);

    sb.append(columnId);

    Integer columnPos = (Integer) request.getAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS);

    sb.append("&p_p_col_pos=");
    sb.append(columnPos);

    Integer columnCount = (Integer) request.getAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT);

    sb.append("&p_p_col_count=");
    sb.append(columnCount);

    if (portlet.isStatic()) {
      sb.append("&p_p_static=1");

      if (portlet.isStaticStart()) {
        sb.append("&p_p_static_start=1");
      }
    }

    sb.append("&p_p_isolated=1");

    String doAsUserId = themeDisplay.getDoAsUserId();

    if (Validator.isNotNull(doAsUserId)) {
      sb.append("&doAsUserId=");
      sb.append(HttpUtil.encodeURL(doAsUserId));
    }

    String currentURL = PortalUtil.getCurrentURL(request);

    sb.append("&currentURL=");
    sb.append(HttpUtil.encodeURL(currentURL));

    String ppid = ParamUtil.getString(request, "p_p_id");

    if (ppid.equals(portletId)) {
      String namespace = PortalUtil.getPortletNamespace(portletId);

      Map<String, String[]> parameters = request.getParameterMap();

      for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
        String name = entry.getKey();

        if (!PortalUtil.isReservedParameter(name)
            && !name.equals("currentURL")
            && !isRefreshURLReservedParameter(name, namespace)) {

          String[] values = entry.getValue();

          for (int i = 0; i < values.length; i++) {
            sb.append(StringPool.AMPERSAND);
            sb.append(name);
            sb.append(StringPool.EQUAL);
            sb.append(HttpUtil.encodeURL(values[i]));
          }
        }
      }
    }

    String outerPortletId = PortalUtil.getOuterPortletId(request);

    if (outerPortletId != null) {
      sb.append(StringPool.AMPERSAND);
      sb.append("p_o_p_id");
      sb.append(StringPool.EQUAL);
      sb.append(HttpUtil.encodeURL(outerPortletId));
    }

    return sb.toString();
  }
  protected void sendEditArticleRedirect(
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      JournalArticle article,
      String oldUrlTitle)
      throws Exception {

    String actionName = ParamUtil.getString(actionRequest, ActionRequest.ACTION_NAME);

    String redirect = ParamUtil.getString(actionRequest, "redirect");

    int workflowAction =
        ParamUtil.getInteger(actionRequest, "workflowAction", WorkflowConstants.ACTION_PUBLISH);

    String portletId = HttpUtil.getParameter(redirect, "p_p_id", false);

    String namespace = PortalUtil.getPortletNamespace(portletId);

    if (Validator.isNotNull(oldUrlTitle)) {
      String oldRedirectParam = namespace + "redirect";

      String oldRedirect = HttpUtil.getParameter(redirect, oldRedirectParam, false);

      if (Validator.isNotNull(oldRedirect)) {
        String newRedirect = HttpUtil.decodeURL(oldRedirect);

        newRedirect = StringUtil.replace(newRedirect, oldUrlTitle, article.getUrlTitle());
        newRedirect = StringUtil.replace(newRedirect, oldRedirectParam, "redirect");

        redirect = StringUtil.replace(redirect, oldRedirect, newRedirect);
      }
    }

    if ((actionName.equals("deleteArticle") || actionName.equals("deleteArticles"))
        && !ActionUtil.hasArticle(actionRequest)) {

      ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

      PortletURL portletURL =
          PortletURLFactoryUtil.create(
              actionRequest,
              themeDisplay.getPpid(),
              themeDisplay.getPlid(),
              PortletRequest.RENDER_PHASE);

      redirect = portletURL.toString();
    }

    if ((article != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

      redirect = getSaveAndContinueRedirect(actionRequest, article, redirect);

      if (actionName.equals("previewArticle")) {
        SessionMessages.add(actionRequest, "previewRequested");

        hideDefaultSuccessMessage(actionRequest);
      }
    } else {
      WindowState windowState = actionRequest.getWindowState();

      if (windowState.equals(LiferayWindowState.POP_UP)) {
        redirect = PortalUtil.escapeRedirect(redirect);

        if (Validator.isNotNull(redirect)) {
          if (actionName.equals("addArticle") && (article != null)) {
            redirect =
                HttpUtil.addParameter(
                    redirect, namespace + "className", JournalArticle.class.getName());
            redirect =
                HttpUtil.addParameter(
                    redirect,
                    namespace + "classPK",
                    JournalArticleAssetRenderer.getClassPK(article));
          }

          actionResponse.sendRedirect(redirect);
        }
      }
    }

    actionRequest.setAttribute(WebKeys.REDIRECT, redirect);
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      BlogsEntry entry = null;
      String oldUrlTitle = StringPool.BLANK;
      List<BlogsEntryAttachmentFileEntryReference> blogsEntryAttachmentFileEntryReferences = null;

      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }

        throw new PortalException(uploadException.getCause());
      } else if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {

        Callable<Object[]> updateEntryCallable = new UpdateEntryCallable(actionRequest);

        Object[] returnValue =
            TransactionInvokerUtil.invoke(_transactionAttribute, updateEntryCallable);

        entry = (BlogsEntry) returnValue[0];
        oldUrlTitle = ((String) returnValue[1]);
        blogsEntryAttachmentFileEntryReferences =
            ((List<BlogsEntryAttachmentFileEntryReference>) returnValue[2]);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteEntries(actionRequest, false);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteEntries(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      } else if (cmd.equals(Constants.SUBSCRIBE)) {
        subscribe(actionRequest);
      } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
        unsubscribe(actionRequest);
      }

      String redirect = ParamUtil.getString(actionRequest, "redirect");
      boolean updateRedirect = false;

      String portletId = HttpUtil.getParameter(redirect, "p_p_id", false);

      if (Validator.isNotNull(oldUrlTitle)) {
        String oldRedirectParam = PortalUtil.getPortletNamespace(portletId) + "redirect";

        String oldRedirect = HttpUtil.getParameter(redirect, oldRedirectParam, false);

        if (Validator.isNotNull(oldRedirect)) {
          String newRedirect = HttpUtil.decodeURL(oldRedirect);

          newRedirect = StringUtil.replace(newRedirect, oldUrlTitle, entry.getUrlTitle());
          newRedirect = StringUtil.replace(newRedirect, oldRedirectParam, "redirect");

          redirect = StringUtil.replace(redirect, oldRedirect, newRedirect);
        } else if (redirect.endsWith("/blogs/" + oldUrlTitle)
            || redirect.contains("/blogs/" + oldUrlTitle + "?")
            || redirect.contains("/blog/" + oldUrlTitle + "?")) {

          redirect = StringUtil.replace(redirect, oldUrlTitle, entry.getUrlTitle());
        }

        updateRedirect = true;
      }

      int workflowAction =
          ParamUtil.getInteger(
              actionRequest, "workflowAction", WorkflowConstants.ACTION_SAVE_DRAFT);

      boolean ajax = ParamUtil.getBoolean(actionRequest, "ajax");

      if (ajax) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

        for (BlogsEntryAttachmentFileEntryReference blogsEntryAttachmentFileEntryReference :
            blogsEntryAttachmentFileEntryReferences) {

          JSONObject blogsEntryFileEntryReferencesJSONObject = JSONFactoryUtil.createJSONObject();

          blogsEntryFileEntryReferencesJSONObject.put(
              "attributeDataImageId", EditorConstants.ATTRIBUTE_DATA_IMAGE_ID);
          blogsEntryFileEntryReferencesJSONObject.put(
              "fileEntryId",
              String.valueOf(
                  blogsEntryAttachmentFileEntryReference.getTempBlogsEntryAttachmentFileEntryId()));
          blogsEntryFileEntryReferencesJSONObject.put(
              "fileEntryUrl",
              PortletFileRepositoryUtil.getPortletFileEntryURL(
                  null,
                  blogsEntryAttachmentFileEntryReference.getBlogsEntryAttachmentFileEntry(),
                  StringPool.BLANK));

          jsonArray.put(blogsEntryFileEntryReferencesJSONObject);
        }

        jsonObject.put("blogsEntryAttachmentReferences", jsonArray);

        jsonObject.put("entryId", entry.getEntryId());
        jsonObject.put("redirect", redirect);
        jsonObject.put("updateRedirect", updateRedirect);

        JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);

        return;
      }

      if ((entry != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

        redirect = getSaveAndContinueRedirect(actionRequest, entry, redirect);

        sendRedirect(actionRequest, actionResponse, redirect);
      } else {
        WindowState windowState = actionRequest.getWindowState();

        if (!windowState.equals(LiferayWindowState.POP_UP)) {
          sendRedirect(actionRequest, actionResponse, redirect);
        } else {
          redirect = PortalUtil.escapeRedirect(redirect);

          if (Validator.isNotNull(redirect)) {
            if (cmd.equals(Constants.ADD) && (entry != null)) {
              String namespace = PortalUtil.getPortletNamespace(portletId);

              redirect =
                  HttpUtil.addParameter(
                      redirect, namespace + "className", BlogsEntry.class.getName());
              redirect = HttpUtil.addParameter(redirect, namespace + "classPK", entry.getEntryId());
            }

            sendRedirect(actionRequest, actionResponse, redirect);
          }
        }
      }
    } catch (Exception e) {
      String mvcPath = "/blogs/edit_entry.jsp";

      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass());

        mvcPath = "/blogs/error.jsp";
      } else if (e instanceof EntryContentException
          || e instanceof EntryCoverImageCropException
          || e instanceof EntryDescriptionException
          || e instanceof EntryDisplayDateException
          || e instanceof EntrySmallImageNameException
          || e instanceof EntrySmallImageScaleException
          || e instanceof EntryTitleException
          || e instanceof FileSizeException
          || e instanceof LiferayFileItemException
          || e instanceof SanitizerException) {

        SessionErrors.add(actionRequest, e.getClass());
      } else if (e instanceof AssetCategoryException || e instanceof AssetTagException) {

        SessionErrors.add(actionRequest, e.getClass(), e);
      } else {
        Throwable cause = e.getCause();

        if (cause instanceof SanitizerException) {
          SessionErrors.add(actionRequest, SanitizerException.class);
        } else {
          throw e;
        }
      }

      actionResponse.setRenderParameter("mvcPath", mvcPath);
    } catch (Throwable t) {
      _log.error(t, t);

      actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");
    }
  }
Пример #11
0
  protected void init(
      HttpServletRequest request,
      Portlet portlet,
      InvokerPortlet invokerPortlet,
      PortletContext portletContext,
      WindowState windowState,
      PortletMode portletMode,
      PortletPreferences preferences,
      long plid) {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    _portlet = portlet;
    _portletName = portlet.getPortletId();
    _publicRenderParameters = PublicRenderParametersPool.get(request, plid);

    String portletNamespace = PortalUtil.getPortletNamespace(_portletName);

    boolean portalSessionShared = false;

    PortletApp portletApp = portlet.getPortletApp();

    if (portletApp.isWARFile() && !portlet.isPrivateSessionAttributes()) {
      portalSessionShared = true;
    }

    request = new SharedSessionServletRequest(request, portalSessionShared);

    DynamicServletRequest dynamicRequest = null;

    if (portlet.isPrivateRequestAttributes()) {
      dynamicRequest =
          new NamespaceServletRequest(request, portletNamespace, portletNamespace, false);
    } else {
      dynamicRequest = new DynamicServletRequest(request, false);
    }

    boolean portletFocus = false;

    String ppid = ParamUtil.getString(request, "p_p_id");

    boolean windowStateRestoreCurrentView = ParamUtil.getBoolean(request, "p_p_state_rcv");

    if (_portletName.equals(ppid)
        && !(windowStateRestoreCurrentView && portlet.isRestoreCurrentView())) {

      // Request was targeted to this portlet

      if (themeDisplay.isLifecycleRender() || themeDisplay.isLifecycleResource()) {

        // Request was triggered by a render or resource URL

        portletFocus = true;
      } else if (themeDisplay.isLifecycleAction()) {
        _triggeredByActionURL = true;

        if (getLifecycle().equals(PortletRequest.ACTION_PHASE)) {

          // Request was triggered by an action URL and is being
          // processed by com.liferay.portlet.ActionRequestImpl

          portletFocus = true;
        }
      }
    }

    Map<String, String[]> renderParameters = RenderParametersPool.get(request, plid, _portletName);

    if (portletFocus) {
      renderParameters = new HashMap<String, String[]>();

      if (getLifecycle().equals(PortletRequest.RENDER_PHASE)
          && !LiferayWindowState.isExclusive(request)
          && !LiferayWindowState.isPopUp(request)) {

        RenderParametersPool.put(request, plid, _portletName, renderParameters);
      }

      Map<String, String[]> parameters = request.getParameterMap();

      for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
        String name = entry.getKey();

        if (isInvalidParameter(name)) {
          continue;
        }

        String[] values = entry.getValue();

        if (themeDisplay.isLifecycleRender()) {
          renderParameters.put(name, values);
        }

        if (values == null) {
          continue;
        }

        name = removePortletNamespace(invokerPortlet, portletNamespace, name);

        dynamicRequest.setParameterValues(name, values);
      }
    } else {
      for (Map.Entry<String, String[]> entry : renderParameters.entrySet()) {

        String name = entry.getKey();
        String[] values = entry.getValue();

        name = removePortletNamespace(invokerPortlet, portletNamespace, name);

        dynamicRequest.setParameterValues(name, values);
      }
    }

    mergePublicRenderParameters(dynamicRequest, preferences, plid);

    _request = dynamicRequest;
    _originalRequest = request;
    _wapTheme = BrowserSnifferUtil.isWap(_request);
    _portlet = portlet;
    _portalContext = new PortalContextImpl();
    _portletContext = portletContext;
    _windowState = windowState;
    _portletMode = portletMode;
    _preferences = preferences;
    _portalSessionId = _request.getRequestedSessionId();
    _session =
        new PortletSessionImpl(_request, _portletName, _portletContext, _portalSessionId, plid);

    String remoteUser = request.getRemoteUser();

    String userPrincipalStrategy = portlet.getUserPrincipalStrategy();

    if (userPrincipalStrategy.equals(PortletConstants.USER_PRINCIPAL_STRATEGY_SCREEN_NAME)) {

      try {
        User user = PortalUtil.getUser(request);

        if (user != null) {
          _remoteUser = user.getScreenName();
          _remoteUserId = user.getUserId();
          _userPrincipal = new ProtectedPrincipal(_remoteUser);
        }
      } catch (Exception e) {
        _log.error(e);
      }
    } else {
      long userId = PortalUtil.getUserId(request);

      if ((userId > 0) && (remoteUser == null)) {
        _remoteUser = String.valueOf(userId);
        _remoteUserId = userId;
        _userPrincipal = new ProtectedPrincipal(_remoteUser);
      } else {
        _remoteUser = remoteUser;
        _remoteUserId = GetterUtil.getLong(remoteUser);
        _userPrincipal = request.getUserPrincipal();
      }
    }

    _locale = themeDisplay.getLocale();
    _plid = plid;
  }
  protected Portlet processPortletRequest(
      HttpServletRequest request, HttpServletResponse response, String lifecycle) throws Exception {

    HttpSession session = request.getSession();

    long companyId = PortalUtil.getCompanyId(request);
    User user = PortalUtil.getUser(request);
    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    String portletId = ParamUtil.getString(request, "p_p_id");

    if (Validator.isNull(portletId)) {
      return null;
    }

    Portlet portlet = PortletLocalServiceUtil.getPortletById(companyId, portletId);

    if (portlet == null) {
      return null;
    }

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    themeDisplay.setScopeGroupId(PortalUtil.getScopeGroupId(request, portletId));

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    if (user != null) {
      InvokerPortletImpl.clearResponse(
          session, layout.getPrimaryKey(), portletId, LanguageUtil.getLanguageId(request));
    }

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    WindowState windowState =
        WindowStateFactory.getWindowState(ParamUtil.getString(request, "p_p_state"));

    if (layout.isTypeControlPanel()
        && ((windowState == null)
            || windowState.equals(WindowState.NORMAL)
            || (Validator.isNull(windowState.toString())))) {

      windowState = WindowState.MAXIMIZED;
    }

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portletId);

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

    processPublicRenderParameters(request, layout, portlet);

    if (lifecycle.equals(PortletRequest.ACTION_PHASE)) {
      String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);

      if (_log.isDebugEnabled()) {
        _log.debug("Content type " + contentType);
      }

      UploadServletRequest uploadRequest = null;

      try {
        if ((contentType != null) && (contentType.startsWith(ContentTypes.MULTIPART_FORM_DATA))) {

          PortletConfigImpl invokerPortletConfigImpl =
              (PortletConfigImpl) invokerPortlet.getPortletConfig();

          if (invokerPortlet.isStrutsPortlet()
              || ((invokerPortletConfigImpl != null) && (!invokerPortletConfigImpl.isWARFile()))) {

            uploadRequest = new UploadServletRequestImpl(request);

            request = uploadRequest;
          }
        }

        if (PropsValues.AUTH_TOKEN_CHECK_ENABLED && invokerPortlet.isCheckAuthToken()) {

          AuthTokenUtil.check(request);
        }

        ActionRequestImpl actionRequestImpl =
            ActionRequestFactory.create(
                request,
                portlet,
                invokerPortlet,
                portletContext,
                windowState,
                portletMode,
                portletPreferences,
                layout.getPlid());

        ActionResponseImpl actionResponseImpl =
            ActionResponseFactory.create(
                actionRequestImpl, response, portletId, user, layout, windowState, portletMode);

        actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);

        ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequestImpl);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);

        invokerPortlet.processAction(actionRequestImpl, actionResponseImpl);

        actionResponseImpl.transferHeaders(response);

        RenderParametersPool.put(
            request, layout.getPlid(), portletId, actionResponseImpl.getRenderParameterMap());

        List<LayoutTypePortlet> layoutTypePortlets = null;

        if (!actionResponseImpl.getEvents().isEmpty()) {
          if (PropsValues.PORTLET_EVENT_DISTRIBUTION_LAYOUT_SET) {
            layoutTypePortlets =
                getLayoutTypePortlets(layout.getGroupId(), layout.isPrivateLayout());
          } else {
            if (layout.isTypePortlet()) {
              LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

              layoutTypePortlets = new ArrayList<LayoutTypePortlet>();

              layoutTypePortlets.add(layoutTypePortlet);
            }
          }

          processEvents(actionRequestImpl, actionResponseImpl, layoutTypePortlets);

          actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);
        }
      } finally {
        if (uploadRequest != null) {
          uploadRequest.cleanUp();
        }

        ServiceContextThreadLocal.popServiceContext();
      }
    } else if (lifecycle.equals(PortletRequest.RENDER_PHASE)
        || lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {

      PortalUtil.updateWindowState(portletId, user, layout, windowState, request);

      PortalUtil.updatePortletMode(portletId, user, layout, portletMode, request);
    }

    if (lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {
      PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

      String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portletId);

      portletDisplay.setId(portletId);
      portletDisplay.setRootPortletId(portlet.getRootPortletId());
      portletDisplay.setInstanceId(portlet.getInstanceId());
      portletDisplay.setResourcePK(portletPrimaryKey);
      portletDisplay.setPortletName(portletConfig.getPortletName());
      portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portletId));

      ResourceRequestImpl resourceRequestImpl =
          ResourceRequestFactory.create(
              request,
              portlet,
              invokerPortlet,
              portletContext,
              windowState,
              portletMode,
              portletPreferences,
              layout.getPlid());

      ResourceResponseImpl resourceResponseImpl =
          ResourceResponseFactory.create(resourceRequestImpl, response, portletId, companyId);

      resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

      try {
        ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequestImpl);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);

        invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);
      } finally {
        ServiceContextThreadLocal.popServiceContext();
      }
    }

    return portlet;
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HeaderCacheServletResponse headerCacheServletResponse = null;

    if (response instanceof HeaderCacheServletResponse) {
      headerCacheServletResponse = (HeaderCacheServletResponse) response;
    } else {
      headerCacheServletResponse = new HeaderCacheServletResponse(response);
    }

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    Layout layout = themeDisplay.getLayout();

    Boolean layoutDefault = (Boolean) request.getAttribute(WebKeys.LAYOUT_DEFAULT);

    if ((layoutDefault != null) && (layoutDefault.booleanValue())) {
      Layout requestedLayout = (Layout) request.getAttribute(WebKeys.REQUESTED_LAYOUT);

      if (requestedLayout != null) {
        String redirectParam = "redirect";

        if (Validator.isNotNull(PropsValues.AUTH_LOGIN_PORTLET_NAME)) {
          redirectParam =
              PortalUtil.getPortletNamespace(PropsValues.AUTH_LOGIN_PORTLET_NAME) + redirectParam;
        }

        String authLoginURL = null;

        if (PrefsPropsUtil.getBoolean(
            themeDisplay.getCompanyId(),
            PropsKeys.CAS_AUTH_ENABLED,
            PropsValues.CAS_AUTH_ENABLED)) {

          authLoginURL = themeDisplay.getURLSignIn();
        }

        if (Validator.isNull(authLoginURL)) {
          authLoginURL = PortalUtil.getCommunityLoginURL(themeDisplay);
        }

        if (Validator.isNull(authLoginURL)) {
          authLoginURL = PropsValues.AUTH_LOGIN_URL;
        }

        if (Validator.isNull(authLoginURL)) {
          PortletURL loginURL = LoginUtil.getLoginURL(request, themeDisplay.getPlid());

          authLoginURL = loginURL.toString();
        }

        String currentURL = PortalUtil.getCurrentURL(request);

        authLoginURL = HttpUtil.setParameter(authLoginURL, redirectParam, currentURL);

        if (_log.isDebugEnabled()) {
          _log.debug("Redirect requested layout to " + authLoginURL);
        }

        headerCacheServletResponse.sendRedirect(authLoginURL);
      } else {
        String redirect = PortalUtil.getLayoutURL(layout, themeDisplay);

        if (_log.isDebugEnabled()) {
          _log.debug("Redirect default layout to " + redirect);
        }

        headerCacheServletResponse.sendRedirect(redirect);
      }

      return null;
    }

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (_log.isDebugEnabled()) {
      _log.debug("p_l_id is " + plid);
    }

    if (plid > 0) {
      ActionForward actionForward =
          processLayout(mapping, request, headerCacheServletResponse, plid);

      String contentType = response.getContentType();

      CacheResponseUtil.setHeaders(response, headerCacheServletResponse.getHeaders());

      if (contentType != null) {
        response.setContentType(contentType);
      }

      return actionForward;
    } else {
      try {
        forwardLayout(request);

        return mapping.findForward(ActionConstants.COMMON_FORWARD_JSP);
      } catch (Exception e) {
        PortalUtil.sendError(e, request, headerCacheServletResponse);

        CacheResponseUtil.setHeaders(response, headerCacheServletResponse.getHeaders());

        return null;
      }
    }
  }
Пример #14
0
  private void _doServeResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    WindowState windowState = (WindowState) request.getAttribute(WebKeys.WINDOW_STATE);

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getStrictPreferences(portletPreferencesIds);

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    String portletPrimaryKey =
        PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId());

    portletDisplay.setControlPanelCategory(portlet.getControlPanelEntryCategory());
    portletDisplay.setId(portlet.getPortletId());
    portletDisplay.setInstanceId(portlet.getInstanceId());
    portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portlet.getPortletId()));
    portletDisplay.setPortletName(portletConfig.getPortletName());
    portletDisplay.setResourcePK(portletPrimaryKey);
    portletDisplay.setRootPortletId(portlet.getRootPortletId());

    WebDAVStorage webDAVStorage = portlet.getWebDAVStorageInstance();

    if (webDAVStorage != null) {
      portletDisplay.setWebDAVEnabled(true);
    } else {
      portletDisplay.setWebDAVEnabled(false);
    }

    ResourceRequestImpl resourceRequestImpl =
        ResourceRequestFactory.create(
            request,
            portlet,
            invokerPortlet,
            portletContext,
            windowState,
            portletMode,
            portletPreferences,
            layout.getPlid());

    long companyId = PortalUtil.getCompanyId(request);

    ResourceResponseImpl resourceResponseImpl =
        ResourceResponseFactory.create(
            resourceRequestImpl, response, portlet.getPortletId(), companyId);

    resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

    try {
      ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);

      resourceResponseImpl.transferHeaders(response);
    } finally {
      ServiceContextThreadLocal.popServiceContext();
    }
  }
  protected String exportToRSS(
      long companyId,
      String name,
      String description,
      String type,
      double version,
      String displayStyle,
      String feedURL,
      String entryURL,
      List<WikiPage> pages,
      boolean diff,
      Locale locale)
      throws SystemException {

    SyndFeed syndFeed = new SyndFeedImpl();

    syndFeed.setFeedType(RSSUtil.getFeedType(type, version));
    syndFeed.setTitle(name);
    syndFeed.setLink(feedURL);
    syndFeed.setDescription(description);

    List<SyndEntry> syndEntries = new ArrayList<SyndEntry>();

    syndFeed.setEntries(syndEntries);

    WikiPage latestPage = null;

    StringBundler link = new StringBundler(7);

    for (WikiPage page : pages) {
      String author = HtmlUtil.escape(PortalUtil.getUserName(page.getUserId(), page.getUserName()));

      String title = page.getTitle() + StringPool.SPACE + page.getVersion();

      if (page.isMinorEdit()) {
        title +=
            StringPool.SPACE
                + StringPool.OPEN_PARENTHESIS
                + LanguageUtil.get(locale, "minor-edit")
                + StringPool.CLOSE_PARENTHESIS;
      }

      link.setIndex(0);

      link.append(entryURL);
      link.append(StringPool.AMPERSAND);
      link.append(HttpUtil.encodeURL(page.getTitle()));

      SyndEntry syndEntry = new SyndEntryImpl();

      syndEntry.setAuthor(author);
      syndEntry.setTitle(title);
      syndEntry.setPublishedDate(page.getCreateDate());
      syndEntry.setUpdatedDate(page.getModifiedDate());

      SyndContent syndContent = new SyndContentImpl();

      syndContent.setType(RSSUtil.ENTRY_TYPE_DEFAULT);

      if (diff) {
        if (latestPage != null) {
          link.append(StringPool.QUESTION);
          link.append(PortalUtil.getPortletNamespace(PortletKeys.WIKI));
          link.append("version=");
          link.append(page.getVersion());

          String value = getPageDiff(companyId, latestPage, page, locale);

          syndContent.setValue(value);

          syndEntry.setDescription(syndContent);

          syndEntries.add(syndEntry);
        }
      } else {
        String value = null;

        if (displayStyle.equals(RSSUtil.DISPLAY_STYLE_ABSTRACT)) {
          value =
              StringUtil.shorten(
                  HtmlUtil.extractText(page.getContent()),
                  PropsValues.WIKI_RSS_ABSTRACT_LENGTH,
                  StringPool.BLANK);
        } else if (displayStyle.equals(RSSUtil.DISPLAY_STYLE_TITLE)) {
          value = StringPool.BLANK;
        } else {
          value = page.getContent();
        }

        syndContent.setValue(value);

        syndEntry.setDescription(syndContent);

        syndEntries.add(syndEntry);
      }

      syndEntry.setLink(link.toString());
      syndEntry.setUri(syndEntry.getLink());

      latestPage = page;
    }

    try {
      return RSSUtil.export(syndFeed);
    } catch (FeedException fe) {
      throw new SystemException(fe);
    }
  }
/**
 * @author Brian Wing Shun Chan
 * @author Berentey Zsolt
 * @author Jorge Ferrer
 * @author Raymond Augé
 */
public class LayoutTypePortletImpl extends LayoutTypeImpl implements LayoutTypePortlet {

  public LayoutTypePortletImpl(
      Layout layout,
      LayoutTypeController layoutTypeController,
      LayoutTypeAccessPolicy layoutTypeAccessPolicy) {

    super(layout, layoutTypeController, layoutTypeAccessPolicy);

    _layoutSetPrototypeLayout = SitesUtil.getLayoutSetPrototypeLayout(layout);
  }

  @Override
  public void addModeAboutPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeAbout(StringUtil.add(getModeAbout(), portletId));
  }

  @Override
  public void addModeConfigPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeConfig(StringUtil.add(getModeConfig(), portletId));
  }

  @Override
  public void addModeEditDefaultsPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeEditDefaults(StringUtil.add(getModeEditDefaults(), portletId));
  }

  @Override
  public void addModeEditGuestPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeEditGuest(StringUtil.add(getModeEditGuest(), portletId));
  }

  @Override
  public void addModeEditPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeEdit(StringUtil.add(getModeEdit(), portletId));
  }

  @Override
  public void addModeHelpPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModeHelp(StringUtil.add(getModeHelp(), portletId));
  }

  @Override
  public void addModePreviewPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModePreview(StringUtil.add(getModePreview(), portletId));
  }

  @Override
  public void addModePrintPortletId(String portletId) {
    removeModesPortletId(portletId);
    setModePrint(StringUtil.add(getModePrint(), portletId));
  }

  @Override
  public String addPortletId(long userId, String portletId) throws PortalException {

    return addPortletId(userId, portletId, true);
  }

  @Override
  public String addPortletId(long userId, String portletId, boolean checkPermission)
      throws PortalException {

    return addPortletId(userId, portletId, null, -1, checkPermission);
  }

  @Override
  public String addPortletId(long userId, String portletId, String columnId, int columnPos)
      throws PortalException {

    return addPortletId(userId, portletId, columnId, columnPos, true);
  }

  @Override
  public String addPortletId(
      long userId, String portletId, String columnId, int columnPos, boolean checkPermission)
      throws PortalException {

    return addPortletId(userId, portletId, columnId, columnPos, checkPermission, false);
  }

  @Override
  public void addPortletIds(long userId, String[] portletIds, boolean checkPermission)
      throws PortalException {

    for (String portletId : portletIds) {
      addPortletId(userId, portletId, checkPermission);
    }
  }

  @Override
  public void addPortletIds(
      long userId, String[] portletIds, String columnId, boolean checkPermission)
      throws PortalException {

    for (String portletId : portletIds) {
      addPortletId(userId, portletId, columnId, -1, checkPermission);
    }
  }

  @Override
  public void addStateMaxPortletId(String portletId) {
    removeStatesPortletId(portletId);
    // setStateMax(StringUtil.add(getStateMax(), portletId));
    setStateMax(StringUtil.add(StringPool.BLANK, portletId));
  }

  @Override
  public void addStateMinPortletId(String portletId) {
    removeStateMaxPortletId(portletId);
    setStateMin(StringUtil.add(getStateMin(), portletId));
  }

  @Override
  public List<Portlet> addStaticPortlets(
      List<Portlet> portlets, List<Portlet> startPortlets, List<Portlet> endPortlets) {

    // Return the original array of portlets if no static portlets are
    // specified

    if (startPortlets == null) {
      startPortlets = new ArrayList<>();
    }

    if (endPortlets == null) {
      endPortlets = new ArrayList<>();
    }

    if (startPortlets.isEmpty() && endPortlets.isEmpty()) {
      return portlets;
    }

    // New array of portlets that contain the static portlets

    List<Portlet> list =
        new ArrayList<>(portlets.size() + startPortlets.size() + endPortlets.size());

    if (!startPortlets.isEmpty()) {
      list.addAll(startPortlets);
    }

    for (int i = 0; i < portlets.size(); i++) {
      Portlet portlet = portlets.get(i);

      // Add the portlet if and only if it is not also a static portlet

      if (!startPortlets.contains(portlet) && !endPortlets.contains(portlet)) {

        list.add(portlet);
      }
    }

    if (!endPortlets.isEmpty()) {
      list.addAll(endPortlets);
    }

    return list;
  }

  @Override
  public List<Portlet> getAllPortlets() throws PortalException {
    List<Portlet> portlets = new ArrayList<>();

    List<String> columns = getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      portlets.addAll(getAllPortlets(columnId));
    }

    List<Portlet> staticPortlets = getStaticPortlets(PropsKeys.LAYOUT_STATIC_PORTLETS_ALL);

    List<Portlet> embeddedPortlets = getEmbeddedPortlets(portlets, staticPortlets);

    return addStaticPortlets(portlets, staticPortlets, embeddedPortlets);
  }

  @Override
  public List<Portlet> getAllPortlets(boolean includeSystem) throws PortalException {

    List<Portlet> filteredPortlets = new ArrayList<>();

    List<Portlet> portlets = getAllPortlets();

    for (Portlet portlet : portlets) {
      if (portlet.isSystem() && !includeSystem) {
        continue;
      }

      filteredPortlets.add(portlet);
    }

    return filteredPortlets;
  }

  @Override
  public List<Portlet> getAllPortlets(String columnId) throws PortalException {

    String columnValue = getColumnValue(columnId);

    String[] portletIds = StringUtil.split(columnValue);

    List<Portlet> portlets = new ArrayList<>(portletIds.length);

    for (String portletId : portletIds) {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if ((portlet != null) && !portlet.isUndeployedPortlet()) {
        portlets.add(portlet);
      }
    }

    List<Portlet> startPortlets =
        getStaticPortlets(PropsKeys.LAYOUT_STATIC_PORTLETS_START + columnId);

    List<Portlet> endPortlets = getStaticPortlets(PropsKeys.LAYOUT_STATIC_PORTLETS_END + columnId);

    return addStaticPortlets(portlets, startPortlets, endPortlets);
  }

  @Override
  public Layout getLayoutSetPrototypeLayout() {
    return _layoutSetPrototypeLayout;
  }

  @Override
  public String getLayoutSetPrototypeLayoutProperty(String key) {
    if (_layoutSetPrototypeLayout == null) {
      return StringPool.BLANK;
    }

    UnicodeProperties typeSettingsProperties =
        _layoutSetPrototypeLayout.getTypeSettingsProperties();

    return typeSettingsProperties.getProperty(key);
  }

  @Override
  public LayoutTemplate getLayoutTemplate() {
    String themeId = getThemeId();

    LayoutTemplate layoutTemplate =
        LayoutTemplateLocalServiceUtil.getLayoutTemplate(getLayoutTemplateId(), false, themeId);

    if (layoutTemplate == null) {
      layoutTemplate = new LayoutTemplateImpl(StringPool.BLANK, StringPool.BLANK);

      List<String> columns = new ArrayList<>();

      for (int i = 1; i <= 10; i++) {
        columns.add(LayoutTypePortletConstants.COLUMN_PREFIX + i);
      }

      layoutTemplate.setColumns(columns);
    }

    return layoutTemplate;
  }

  @Override
  public String getLayoutTemplateId() {
    return GetterUtil.getString(
        getTypeSettingsProperty(LayoutTypePortletConstants.LAYOUT_TEMPLATE_ID));
  }

  @Override
  public String getModeAbout() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_ABOUT);
  }

  @Override
  public String getModeConfig() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_CONFIG);
  }

  @Override
  public String getModeEdit() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT);
  }

  @Override
  public String getModeEditDefaults() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
  }

  @Override
  public String getModeEditGuest() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
  }

  @Override
  public String getModeHelp() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_HELP);
  }

  @Override
  public String getModePreview() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_PREVIEW);
  }

  @Override
  public String getModePrint() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.MODE_PRINT);
  }

  @Override
  public int getNumOfColumns() {
    return getLayoutTemplate().getColumns().size();
  }

  @Override
  public PortalPreferences getPortalPreferences() {
    return _portalPreferences;
  }

  @Override
  public List<String> getPortletIds() {
    List<String> portletIds = new ArrayList<>();

    List<String> columns = getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      String columnValue = getColumnValue(columnId);

      portletIds.addAll(ListUtil.fromArray(StringUtil.split(columnValue)));
    }

    return portletIds;
  }

  @Override
  public List<Portlet> getPortlets() {
    List<String> portletIds = getPortletIds();

    List<Portlet> portlets = new ArrayList<>(portletIds.size());

    for (int i = 0; i < portletIds.size(); i++) {
      String portletId = portletIds.get(i);

      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (portlet != null) {
        portlets.add(portlet);
      }
    }

    return portlets;
  }

  @Override
  public String getStateMax() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.STATE_MAX);
  }

  @Override
  public String getStateMaxPortletId() {
    String[] stateMax = StringUtil.split(getStateMax());

    if (stateMax.length > 0) {
      return stateMax[0];
    } else {
      return StringPool.BLANK;
    }
  }

  @Override
  public String getStateMin() {
    return getTypeSettingsProperty(LayoutTypePortletConstants.STATE_MIN);
  }

  @Override
  public boolean hasDefaultScopePortletId(long groupId, String portletId) throws PortalException {

    if (hasPortletId(portletId)) {
      long scopeGroupId = PortalUtil.getScopeGroupId(getLayout(), portletId);

      if (groupId == scopeGroupId) {
        return true;
      }
    }

    return false;
  }

  @Override
  public boolean hasModeAboutPortletId(String portletId) {
    return StringUtil.contains(getModeAbout(), portletId);
  }

  @Override
  public boolean hasModeConfigPortletId(String portletId) {
    return StringUtil.contains(getModeConfig(), portletId);
  }

  @Override
  public boolean hasModeEditDefaultsPortletId(String portletId) {
    return StringUtil.contains(getModeEditDefaults(), portletId);
  }

  @Override
  public boolean hasModeEditGuestPortletId(String portletId) {
    return StringUtil.contains(getModeEditGuest(), portletId);
  }

  @Override
  public boolean hasModeEditPortletId(String portletId) {
    return StringUtil.contains(getModeEdit(), portletId);
  }

  @Override
  public boolean hasModeHelpPortletId(String portletId) {
    return StringUtil.contains(getModeHelp(), portletId);
  }

  @Override
  public boolean hasModePreviewPortletId(String portletId) {
    return StringUtil.contains(getModePreview(), portletId);
  }

  @Override
  public boolean hasModePrintPortletId(String portletId) {
    return StringUtil.contains(getModePrint(), portletId);
  }

  @Override
  public boolean hasModeViewPortletId(String portletId) {
    if (hasModeAboutPortletId(portletId)
        || hasModeConfigPortletId(portletId)
        || hasModeEditPortletId(portletId)
        || hasModeEditDefaultsPortletId(portletId)
        || hasModeEditGuestPortletId(portletId)
        || hasModeHelpPortletId(portletId)
        || hasModePreviewPortletId(portletId)
        || hasModePrintPortletId(portletId)) {

      return false;
    } else {
      return true;
    }
  }

  @Override
  public boolean hasPortletId(String portletId) throws PortalException {
    return hasPortletId(portletId, false);
  }

  @Override
  public boolean hasPortletId(String portletId, boolean strict) throws PortalException {

    List<String> columns = getColumns();

    for (String columnId : columns) {
      if (hasNonstaticPortletId(columnId, portletId)) {
        return true;
      }

      if (hasStaticPortletId(columnId, portletId)) {
        return true;
      }
    }

    Layout layout = getLayout();

    if (layout.isTypeControlPanel()) {
      return false;
    }

    if (isCustomizable() && isCustomizedView()) {
      LayoutTypePortletImpl defaultLayoutTypePortletImpl = getDefaultLayoutTypePortletImpl();

      if (defaultLayoutTypePortletImpl.hasNonstaticPortletId(portletId)) {
        return false;
      }
    }

    if (!strict
        && ((PortletPreferencesLocalServiceUtil.getPortletPreferencesCount(
                    PortletKeys.PREFS_OWNER_TYPE_LAYOUT, layout.getPlid(), portletId)
                > 0)
            || (PortletPreferencesLocalServiceUtil.getPortletPreferencesCount(
                    PortletKeys.PREFS_OWNER_TYPE_USER, layout.getPlid(), portletId)
                > 0))) {

      return true;
    }

    return false;
  }

  @Override
  public boolean hasStateMax() {
    String[] stateMax = StringUtil.split(getStateMax());

    if (stateMax.length > 0) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  public boolean hasStateMaxPortletId(String portletId) {
    if (StringUtil.contains(getStateMax(), portletId)) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  public boolean hasStateMin() {
    String[] stateMin = StringUtil.split(getStateMin());

    if (stateMin.length > 0) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  public boolean hasStateMinPortletId(String portletId) {
    if (StringUtil.contains(getStateMin(), portletId)) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  public boolean hasStateNormalPortletId(String portletId) {
    if (hasStateMaxPortletId(portletId) || hasStateMinPortletId(portletId)) {

      return false;
    } else {
      return true;
    }
  }

  @Override
  public boolean hasUpdatePermission() {
    return _updatePermission;
  }

  @Override
  public boolean isCacheable() throws PortalException {
    for (String columnId : getColumns()) {
      for (Portlet portlet : getAllPortlets(columnId)) {
        Portlet rootPortlet = portlet.getRootPortlet();

        if (!rootPortlet.isLayoutCacheable()) {
          return false;
        }
      }
    }

    return true;
  }

  @Override
  public boolean isColumnCustomizable(String columnId) {
    if (!isLayoutSetPrototype()) {
      String customizableString =
          getTypeSettingsProperty(CustomizedPages.namespaceColumnId(columnId));

      boolean customizable = GetterUtil.getBoolean(customizableString);

      if (!customizable && hasUserPreferences()) {
        String columnValue =
            _portalPreferences.getValue(
                CustomizedPages.namespacePlid(getPlid()), columnId, StringPool.NULL);

        if (!Validator.equals(columnValue, StringPool.NULL)) {
          setUserPreference(columnId, null);
        }
      }

      return customizable;
    }

    return false;
  }

  @Override
  public boolean isColumnDisabled(String columnId) {
    if ((isCustomizedView() && !isColumnCustomizable(columnId))
        || (!isCustomizedView() && !hasUpdatePermission())) {

      return true;
    }

    return false;
  }

  @Override
  public boolean isCustomizable() {
    for (String columnId : getColumns()) {
      if (isColumnCustomizable(columnId)) {
        return true;
      }
    }

    return false;
  }

  @Override
  public boolean isCustomizedView() {
    return _customizedView;
  }

  @Override
  public boolean isDefaultUpdated() {
    if (!isCustomizedView() || !hasUserPreferences()) {
      return false;
    }

    String preferencesModifiedDateString =
        _portalPreferences.getValue(
            CustomizedPages.namespacePlid(getPlid()), _MODIFIED_DATE, _NULL_DATE);

    DateFormat dateFormat =
        DateFormatFactoryUtil.getSimpleDateFormat(PropsValues.INDEX_DATE_FORMAT_PATTERN);

    try {
      Date preferencesModifiedDate = dateFormat.parse(preferencesModifiedDateString);

      Layout layout = getLayout();

      String propertiesModifiedDateString =
          layout.getTypeSettingsProperty(_MODIFIED_DATE, _NULL_DATE);

      Date propertiesModifiedDate = dateFormat.parse(propertiesModifiedDateString);

      return propertiesModifiedDate.after(preferencesModifiedDate);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return false;
  }

  @Override
  public boolean isPortletCustomizable(String portletId) {
    return isColumnCustomizable(getColumn(portletId));
  }

  @Override
  public void movePortletId(long userId, String portletId, String columnId, int columnPos)
      throws PortalException {

    if (!hasPortletId(portletId)) {
      return;
    }

    _enablePortletLayoutListener = false;

    try {
      removePortletId(userId, portletId, false);
      addPortletId(userId, portletId, columnId, columnPos, false, true);
    } finally {
      _enablePortletLayoutListener = true;
    }

    Layout layout = getLayout();

    try {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

      if (portlet != null) {
        PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

        if (portletLayoutListener != null) {
          portletLayoutListener.onMoveInLayout(portletId, layout.getPlid());
        }
      }
    } catch (Exception e) {
      _log.error("Unable to fire portlet layout listener event", e);
    }
  }

  @Override
  public void removeModeAboutPortletId(String portletId) {
    setModeAbout(StringUtil.removeFromList(getModeAbout(), portletId));
  }

  @Override
  public void removeModeConfigPortletId(String portletId) {
    setModeConfig(StringUtil.removeFromList(getModeConfig(), portletId));
  }

  @Override
  public void removeModeEditDefaultsPortletId(String portletId) {
    setModeEditDefaults(StringUtil.removeFromList(getModeEditDefaults(), portletId));
  }

  @Override
  public void removeModeEditGuestPortletId(String portletId) {
    setModeEditGuest(StringUtil.removeFromList(getModeEditGuest(), portletId));
  }

  @Override
  public void removeModeEditPortletId(String portletId) {
    setModeEdit(StringUtil.removeFromList(getModeEdit(), portletId));
  }

  @Override
  public void removeModeHelpPortletId(String portletId) {
    setModeHelp(StringUtil.removeFromList(getModeHelp(), portletId));
  }

  @Override
  public void removeModePreviewPortletId(String portletId) {
    setModePreview(StringUtil.removeFromList(getModePreview(), portletId));
  }

  @Override
  public void removeModePrintPortletId(String portletId) {
    setModePrint(StringUtil.removeFromList(getModePrint(), portletId));
  }

  @Override
  public void removeModesPortletId(String portletId) {
    removeModeAboutPortletId(portletId);
    removeModeConfigPortletId(portletId);
    removeModeEditPortletId(portletId);
    removeModeEditDefaultsPortletId(portletId);
    removeModeEditGuestPortletId(portletId);
    removeModeHelpPortletId(portletId);
    removeModePreviewPortletId(portletId);
    removeModePrintPortletId(portletId);
  }

  @Override
  public void removeNestedColumns(String portletNamespace) {
    UnicodeProperties typeSettingsProperties = getTypeSettingsProperties();

    UnicodeProperties newTypeSettingsProperties = new UnicodeProperties();

    for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

      String key = entry.getKey();

      if (!key.startsWith(portletNamespace)) {
        newTypeSettingsProperties.setProperty(key, entry.getValue());
      }
    }

    Layout layout = getLayout();

    layout.setTypeSettingsProperties(newTypeSettingsProperties);

    String nestedColumnIds =
        GetterUtil.getString(getTypeSettingsProperty(LayoutTypePortletConstants.NESTED_COLUMN_IDS));

    String[] nestedColumnIdsArray =
        ArrayUtil.removeByPrefix(StringUtil.split(nestedColumnIds), portletNamespace);

    setTypeSettingsProperty(
        LayoutTypePortletConstants.NESTED_COLUMN_IDS, StringUtil.merge(nestedColumnIdsArray));
  }

  @Override
  public void removePortletId(long userId, String portletId) {
    removePortletId(userId, portletId, true);
  }

  @Override
  public void removePortletId(long userId, String portletId, boolean cleanUp) {

    try {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (portlet == null) {
        _log.error("Portlet " + portletId + " cannot be removed because it is not registered");

        return;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (!LayoutPermissionUtil.contains(permissionChecker, getLayout(), ActionKeys.UPDATE)
          && !isCustomizable()) {

        return;
      }
    } catch (Exception e) {
      _log.error(e, e);

      return;
    }

    List<String> columns = getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      if (isCustomizable() && isColumnDisabled(columnId)) {
        continue;
      }

      String columnValue = StringPool.BLANK;

      if (hasUserPreferences()) {
        columnValue = getUserPreference(columnId);
      } else {
        columnValue = getTypeSettingsProperty(columnId);
      }

      columnValue = StringUtil.removeFromList(columnValue, portletId);

      if (hasUserPreferences()) {
        setUserPreference(columnId, columnValue);
      } else {
        setTypeSettingsProperty(columnId, columnValue);
      }
    }

    if (cleanUp) {
      try {
        onRemoveFromLayout(new String[] {portletId});
      } catch (Exception e) {
        _log.error(e, e);
      }
    }
  }

  @Override
  public void removeStateMaxPortletId(String portletId) {
    setStateMax(StringUtil.removeFromList(getStateMax(), portletId));
  }

  @Override
  public void removeStateMinPortletId(String portletId) {
    setStateMin(StringUtil.removeFromList(getStateMin(), portletId));
  }

  @Override
  public void removeStatesPortletId(String portletId) {
    removeStateMaxPortletId(portletId);
    removeStateMinPortletId(portletId);
  }

  @Override
  public void reorganizePortlets(List<String> newColumns, List<String> oldColumns) {

    String lastNewColumnId = newColumns.get(newColumns.size() - 1);
    String lastNewColumnValue = getTypeSettingsProperty(lastNewColumnId);

    for (String oldColumnId : oldColumns) {
      if (!newColumns.contains(oldColumnId)) {
        String oldColumnValue = getTypeSettingsProperties().remove(oldColumnId);

        String[] portletIds = StringUtil.split(oldColumnValue);

        for (String portletId : portletIds) {
          lastNewColumnValue = StringUtil.add(lastNewColumnValue, portletId);
        }
      }
    }

    setTypeSettingsProperty(lastNewColumnId, lastNewColumnValue);
  }

  @Override
  public void resetModes() {
    setModeAbout(StringPool.BLANK);
    setModeConfig(StringPool.BLANK);
    setModeEdit(StringPool.BLANK);
    setModeEditDefaults(StringPool.BLANK);
    setModeEditGuest(StringPool.BLANK);
    setModeHelp(StringPool.BLANK);
    setModePreview(StringPool.BLANK);
    setModePrint(StringPool.BLANK);
  }

  @Override
  public void resetStates() {
    setStateMax(StringPool.BLANK);
    setStateMin(StringPool.BLANK);
  }

  @Override
  public void resetUserPreferences() {
    if (!hasUserPreferences()) {
      return;
    }

    long plid = getPlid();

    Set<String> customPortletIds = new HashSet<>();

    for (String columnId : getColumns()) {
      String value = _portalPreferences.getValue(CustomizedPages.namespacePlid(plid), columnId);

      for (String customPortletId : StringUtil.split(value)) {
        customPortletIds.add(customPortletId);
      }
    }

    try {
      onRemoveFromLayout(customPortletIds.toArray(new String[customPortletIds.size()]));
    } catch (Exception e) {
      _log.error(e, e);
    }

    _portalPreferences.resetValues(CustomizedPages.namespacePlid(plid));

    _portalPreferences.setValue(
        CustomizedPages.namespacePlid(plid), _MODIFIED_DATE, _dateFormat.format(new Date()));
  }

  @Override
  public void setCustomizedView(boolean customizedView) {
    _customizedView = customizedView;
  }

  @Override
  public void setLayoutTemplateId(long userId, String newLayoutTemplateId) {
    setLayoutTemplateId(userId, newLayoutTemplateId, true);
  }

  @Override
  public void setLayoutTemplateId(
      long userId, String newLayoutTemplateId, boolean checkPermission) {

    if (checkPermission
        && !PluginSettingLocalServiceUtil.hasPermission(
            userId, newLayoutTemplateId, Plugin.TYPE_LAYOUT_TEMPLATE)) {

      return;
    }

    LayoutTemplate oldLayoutTemplate = getLayoutTemplate();

    String themeId = getThemeId();

    LayoutTemplate newLayoutTemplate =
        LayoutTemplateLocalServiceUtil.getLayoutTemplate(newLayoutTemplateId, false, themeId);

    if (newLayoutTemplate == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("Unable to find layout template " + newLayoutTemplateId);
      }

      return;
    }

    setTypeSettingsProperty(LayoutTypePortletConstants.LAYOUT_TEMPLATE_ID, newLayoutTemplateId);

    List<String> oldColumns = oldLayoutTemplate.getColumns();
    List<String> newColumns = newLayoutTemplate.getColumns();

    reorganizePortlets(newColumns, oldColumns);
  }

  @Override
  public void setModeAbout(String modeAbout) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_ABOUT, modeAbout);
  }

  @Override
  public void setModeConfig(String modeConfig) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_CONFIG, modeConfig);
  }

  @Override
  public void setModeEdit(String modeEdit) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT, modeEdit);
  }

  @Override
  public void setModeEditDefaults(String modeEditDefaults) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS, modeEditDefaults);
  }

  @Override
  public void setModeEditGuest(String modeEditGuest) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST, modeEditGuest);
  }

  @Override
  public void setModeHelp(String modeHelp) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_HELP, modeHelp);
  }

  @Override
  public void setModePreview(String modePreview) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_PREVIEW, modePreview);
  }

  @Override
  public void setModePrint(String modePrint) {
    setTypeSettingsProperty(LayoutTypePortletConstants.MODE_PRINT, modePrint);
  }

  @Override
  public void setPortalPreferences(PortalPreferences portalPreferences) {
    _portalPreferences = portalPreferences;
  }

  @Override
  public void setStateMax(String stateMax) {
    setTypeSettingsProperty(LayoutTypePortletConstants.STATE_MAX, stateMax);
  }

  @Override
  public void setStateMin(String stateMin) {
    setTypeSettingsProperty(LayoutTypePortletConstants.STATE_MIN, stateMin);
  }

  @Override
  public void setUpdatePermission(boolean updatePermission) {
    _updatePermission = updatePermission;
  }

  protected void addNestedColumn(String columnId) {
    String nestedColumnIds =
        getTypeSettingsProperty(LayoutTypePortletConstants.NESTED_COLUMN_IDS, StringPool.BLANK);

    if (!nestedColumnIds.contains(columnId)) {
      nestedColumnIds = StringUtil.add(nestedColumnIds, columnId);

      setTypeSettingsProperty(LayoutTypePortletConstants.NESTED_COLUMN_IDS, nestedColumnIds);
    }
  }

  protected String addPortletId(
      long userId,
      String portletId,
      String columnId,
      int columnPos,
      boolean checkPermission,
      boolean strictHasPortlet)
      throws PortalException {

    portletId = JS.getSafeName(portletId);

    Layout layout = getLayout();

    Portlet portlet = null;

    try {
      portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

      if (portlet == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Portlet " + portletId + " cannot be added because it is not registered");
        }

        return null;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (checkPermission
          && !PortletPermissionUtil.contains(
              permissionChecker, layout, portlet, ActionKeys.ADD_TO_PAGE)) {

        return null;
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (portlet.isSystem()) {
      return null;
    }

    if (portlet.isInstanceable() && !PortletConstants.hasInstanceId(portletId)) {

      portletId =
          PortletConstants.assemblePortletId(portletId, PortletConstants.generateInstanceId());
    }

    if (hasPortletId(portletId, strictHasPortlet)) {
      return null;
    }

    if (columnId == null) {
      LayoutTemplate layoutTemplate = getLayoutTemplate();

      List<String> columns = layoutTemplate.getColumns();

      if (!columns.isEmpty()) {
        columnId = columns.get(0);
      }
    }

    if (columnId == null) {
      return null;
    }

    if (isCustomizable()) {
      if (isColumnDisabled(columnId)) {
        return null;
      }

      if ((PortletConstants.hasInstanceId(portletId) || portlet.isPreferencesUniquePerLayout())
          && hasUserPreferences()) {

        portletId = PortletConstants.assemblePortletId(portletId, userId);
      }
    }

    String columnValue = StringPool.BLANK;

    if (hasUserPreferences()) {
      columnValue = getUserPreference(columnId);
    } else {
      columnValue = getTypeSettingsProperty(columnId);
    }

    if ((columnValue == null) && columnId.startsWith(_NESTED_PORTLETS_NAMESPACE)) {

      addNestedColumn(columnId);
    }

    if (columnPos >= 0) {
      List<String> portletIds = ListUtil.fromArray(StringUtil.split(columnValue));

      if (columnPos <= portletIds.size()) {
        portletIds.add(columnPos, portletId);
      } else {
        portletIds.add(portletId);
      }

      columnValue = StringUtil.merge(portletIds);
    } else {
      columnValue = StringUtil.add(columnValue, portletId);
    }

    if (hasUserPreferences()) {
      setUserPreference(columnId, columnValue);
    } else {
      setTypeSettingsProperty(columnId, columnValue);
    }

    try {
      if (_enablePortletLayoutListener) {
        PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

        if (portletLayoutListener != null) {
          portletLayoutListener.onAddToLayout(portletId, layout.getPlid());
        }
      }
    } catch (Exception e) {
      _log.error("Unable to fire portlet layout listener event", e);
    }

    return portletId;
  }

  protected void copyPreferences(long userId, String sourcePortletId, String targetPortletId) {

    Layout layout = getLayout();

    try {
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), 0, layout, sourcePortletId, false);

      javax.portlet.PortletPreferences sourcePortletPreferences =
          PortletPreferencesLocalServiceUtil.getStrictPreferences(portletPreferencesIds);

      portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), userId, layout, targetPortletId, false);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePortletPreferences);
    } catch (Exception e) {
    }
  }

  protected String getColumn(String portletId) {
    String portletIdColumnId = StringPool.BLANK;

    List<String> columnIds = getColumns();

    for (String columnId : columnIds) {
      String columnValue = getColumnValue(columnId);

      String[] portletIds = StringUtil.split(columnValue);

      for (String columnPortletId : portletIds) {
        if (columnPortletId.equals(portletId)) {
          return columnId;
        }

        if (Validator.isNull(portletIdColumnId)
            && PortletConstants.hasIdenticalRootPortletId(columnPortletId, portletId)) {

          portletIdColumnId = columnId;
        }
      }
    }

    return portletIdColumnId;
  }

  protected List<String> getColumns() {
    List<String> columns = new ArrayList<>();

    Layout layout = getLayout();

    if (layout.isTypePortlet()) {
      LayoutTemplate layoutTemplate = getLayoutTemplate();

      columns.addAll(layoutTemplate.getColumns());

      columns.addAll(getNestedColumns());
    } else if (layout.isTypePanel()) {
      columns.add("panelSelectedPortlets");
    }

    return columns;
  }

  protected String getColumnValue(String columnId) {
    if (hasUserPreferences() && isCustomizable() && !isColumnDisabled(columnId)) {

      return getUserPreference(columnId);
    }

    return getTypeSettingsProperty(columnId);
  }

  protected long getCompanyId() {
    Layout layout = getLayout();

    return layout.getCompanyId();
  }

  protected LayoutTypePortletImpl getDefaultLayoutTypePortletImpl() {
    if (!isCustomizedView()) {
      return this;
    }

    LayoutTypePortletImpl defaultLayoutTypePortletImpl =
        (LayoutTypePortletImpl) LayoutTypePortletFactoryUtil.create(getLayout());

    defaultLayoutTypePortletImpl._embeddedPortlets = _embeddedPortlets;
    defaultLayoutTypePortletImpl._layoutSetPrototypeLayout = _layoutSetPrototypeLayout;
    defaultLayoutTypePortletImpl._updatePermission = _updatePermission;

    return defaultLayoutTypePortletImpl;
  }

  protected List<Portlet> getEmbeddedPortlets(
      List<Portlet> columnPortlets, List<Portlet> staticPortlets) {

    if (_embeddedPortlets != null) {
      return _embeddedPortlets;
    }

    List<Portlet> portlets = new ArrayList<>();

    Layout layout = getLayout();

    List<PortletPreferences> portletPreferences =
        PortletPreferencesLocalServiceUtil.getPortletPreferences(
            PortletKeys.PREFS_OWNER_ID_DEFAULT,
            PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
            layout.getPlid());

    if (isCustomizable() && hasUserPreferences()) {
      portletPreferences = ListUtil.copy(portletPreferences);

      portletPreferences.addAll(
          PortletPreferencesLocalServiceUtil.getPortletPreferences(
              _portalPreferences.getUserId(), PortletKeys.PREFS_OWNER_TYPE_USER, layout.getPlid()));
    }

    for (PortletPreferences portletPreference : portletPreferences) {
      String portletId = portletPreference.getPortletId();

      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (Validator.isNull(portletId)
          || columnPortlets.contains(portlet)
          || staticPortlets.contains(portlet)
          || !portlet.isReady()
          || portlet.isUndeployedPortlet()
          || !portlet.isActive()) {

        continue;
      }

      if (portlet != null) {
        Portlet embeddedPortlet = portlet;

        if (portlet.isInstanceable()) {

          // Instanceable portlets do not need to be cloned because
          // they are already cloned. See the method getPortletById in
          // the class PortletLocalServiceImpl and how it references
          // the method getClonedInstance in the class PortletImpl.

        } else {
          embeddedPortlet = (Portlet) embeddedPortlet.clone();
        }

        // We set embedded portlets as static on order to avoid adding
        // the close and/or move icons.

        embeddedPortlet.setStatic(true);

        portlets.add(embeddedPortlet);
      }
    }

    _embeddedPortlets = portlets;

    return _embeddedPortlets;
  }

  protected List<String> getNestedColumns() {
    String nestedColumnIds = getTypeSettingsProperty(LayoutTypePortletConstants.NESTED_COLUMN_IDS);

    return ListUtil.fromArray(StringUtil.split(nestedColumnIds));
  }

  protected long getPlid() {
    Layout layout = getLayout();

    return layout.getPlid();
  }

  protected String[] getStaticPortletIds(String position) throws PortalException {

    Layout layout = getLayout();

    String selector1 = StringPool.BLANK;

    Group group = layout.getGroup();

    if (group.isUser()) {
      selector1 = LayoutTypePortletConstants.STATIC_PORTLET_USER_SELECTOR;
    } else if (group.isOrganization()) {
      selector1 = LayoutTypePortletConstants.STATIC_PORTLET_ORGANIZATION_SELECTOR;
    } else if (group.isRegularSite()) {
      selector1 = LayoutTypePortletConstants.STATIC_PORTLET_REGULAR_SITE_SELECTOR;
    }

    String selector2 = layout.getFriendlyURL();

    String[] portletIds = PropsUtil.getArray(position, new Filter(selector1, selector2));

    for (int i = 0; i < portletIds.length; i++) {
      portletIds[i] = JS.getSafeName(portletIds[i]);
    }

    return portletIds;
  }

  protected List<Portlet> getStaticPortlets(String position) throws PortalException {

    String[] portletIds = getStaticPortletIds(position);

    List<Portlet> portlets = new ArrayList<>();

    for (String portletId : portletIds) {
      if (Validator.isNull(portletId) || hasNonstaticPortletId(portletId)) {

        continue;
      }

      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (portlet != null) {
        Portlet staticPortlet = portlet;

        if (portlet.isInstanceable()) {

          // Instanceable portlets do not need to be cloned because
          // they are already cloned. See the method getPortletById in
          // the class PortletLocalServiceImpl and how it references
          // the method getClonedInstance in the class PortletImpl.

        } else {
          staticPortlet = (Portlet) staticPortlet.clone();
        }

        staticPortlet.setStatic(true);

        if (position.startsWith("layout.static.portlets.start")) {
          staticPortlet.setStaticStart(true);
        }

        portlets.add(staticPortlet);
      }
    }

    return portlets;
  }

  protected String getThemeId() {
    String themeId = null;

    try {
      Layout layout = getLayout();

      Theme theme = layout.getTheme();

      if (theme != null) {
        themeId = theme.getThemeId();
      } else {
        themeId = layout.getThemeId();
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return themeId;
  }

  protected String getUserPreference(String key) {
    String value = StringPool.BLANK;

    if (!hasUserPreferences()) {
      return value;
    }

    value =
        _portalPreferences.getValue(CustomizedPages.namespacePlid(getPlid()), key, StringPool.NULL);

    if (!value.equals(StringPool.NULL)) {
      return value;
    }

    value = getTypeSettingsProperty(key);

    if (Validator.isNull(value)) {
      return value;
    }

    List<String> newPortletIds = new ArrayList<>();

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    String[] portletIds = StringUtil.split(value);

    for (String portletId : portletIds) {
      try {
        String rootPortletId = PortletConstants.getRootPortletId(portletId);

        if (!PortletPermissionUtil.contains(
            permissionChecker, rootPortletId, ActionKeys.ADD_TO_PAGE)) {

          continue;
        }
      } catch (Exception e) {
        _log.error(e, e);
      }

      String newPortletId = null;

      boolean preferencesUniquePerLayout = false;

      try {
        Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

        preferencesUniquePerLayout = portlet.isPreferencesUniquePerLayout();
      } catch (SystemException se) {
        _log.error(se, se);
      }

      if (PortletConstants.hasInstanceId(portletId) || preferencesUniquePerLayout) {

        String instanceId = null;

        if (PortletConstants.hasInstanceId(portletId)) {
          instanceId = PortletConstants.generateInstanceId();
        }

        newPortletId =
            PortletConstants.assemblePortletId(
                portletId, _portalPreferences.getUserId(), instanceId);

        copyPreferences(_portalPreferences.getUserId(), portletId, newPortletId);
      } else {
        newPortletId = portletId;
      }

      newPortletIds.add(newPortletId);
    }

    value = StringUtil.merge(newPortletIds);

    setUserPreference(key, value);

    return value;
  }

  protected boolean hasNonstaticPortletId(String portletId) {
    LayoutTemplate layoutTemplate = getLayoutTemplate();

    List<String> columns = layoutTemplate.getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      if (hasNonstaticPortletId(columnId, portletId)) {
        return true;
      }
    }

    return false;
  }

  protected boolean hasNonstaticPortletId(String columnId, String portletId) {
    String columnValue = getColumnValue(columnId);

    String[] columnValues = StringUtil.split(columnValue);

    for (String nonstaticPortletId : columnValues) {
      if (nonstaticPortletId.equals(portletId)
          || PortletConstants.getRootPortletId(nonstaticPortletId).equals(portletId)) {

        return true;
      }
    }

    return false;
  }

  protected boolean hasStaticPortletId(String columnId, String portletId) throws PortalException {

    String[] staticPortletIdsStart =
        getStaticPortletIds(PropsKeys.LAYOUT_STATIC_PORTLETS_START + columnId);

    String[] staticPortletIdsEnd =
        getStaticPortletIds(PropsKeys.LAYOUT_STATIC_PORTLETS_END + columnId);

    for (String staticPortletId : staticPortletIdsStart) {
      if (staticPortletId.equals(portletId)
          || PortletConstants.getRootPortletId(staticPortletId).equals(portletId)) {

        return true;
      }
    }

    for (String staticPortletId : staticPortletIdsEnd) {
      if (staticPortletId.equals(portletId)
          || PortletConstants.getRootPortletId(staticPortletId).equals(portletId)) {

        return true;
      }
    }

    return false;
  }

  protected boolean hasUserPreferences() {
    if (_portalPreferences != null) {
      return true;
    }

    return false;
  }

  protected boolean isLayoutSetPrototype() {
    try {
      Layout layout = getLayout();

      LayoutSet layoutSet = layout.getLayoutSet();

      Group group = layoutSet.getGroup();

      return group.isLayoutSetPrototype();
    } catch (Exception e) {
      _log.error(e, e);
    }

    return false;
  }

  protected void onRemoveFromLayout(String[] portletIds) {
    Set<String> portletIdList = new HashSet<>();

    for (String portletId : portletIds) {
      removeModesPortletId(portletId);
      removeStatesPortletId(portletId);

      portletIdList.add(portletId);

      String rootPortletId = PortletConstants.getRootPortletId(portletId);

      if (rootPortletId.equals(PortletKeys.NESTED_PORTLETS)) {
        String portletNamespace = PortalUtil.getPortletNamespace(portletId);

        UnicodeProperties typeSettingsProperties = getTypeSettingsProperties();

        for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

          String key = entry.getKey();

          if (!key.startsWith(portletNamespace)) {
            continue;
          }

          String nestedPortletIds = entry.getValue();

          for (String nestedPortletId : StringUtil.split(nestedPortletIds)) {

            removeModesPortletId(nestedPortletId);
            removeStatesPortletId(nestedPortletId);

            portletIdList.add(nestedPortletId);
          }
        }

        removeNestedColumns(portletNamespace);
      }

      Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId);

      if (portlet == null) {
        continue;
      }

      PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

      if (portletLayoutListener == null) {
        continue;
      }

      portletLayoutListener.updatePropertiesOnRemoveFromLayout(
          portletId, getTypeSettingsProperties());
    }

    try {
      PortletLocalServiceUtil.deletePortlets(
          getCompanyId(), portletIdList.toArray(new String[portletIdList.size()]), getPlid());
    } catch (PortalException pe) {
      _log.error(pe, pe);
    }
  }

  protected void setUserPreference(String key, String value) {
    if (!hasUserPreferences()) {
      return;
    }

    _portalPreferences.setValue(CustomizedPages.namespacePlid(getPlid()), key, value);

    _portalPreferences.setValue(
        CustomizedPages.namespacePlid(getPlid()), _MODIFIED_DATE, _dateFormat.format(new Date()));
  }

  private static final String _MODIFIED_DATE = "modifiedDate";

  private static final String _NESTED_PORTLETS_NAMESPACE =
      PortalUtil.getPortletNamespace(PortletKeys.NESTED_PORTLETS);

  private static final String _NULL_DATE = "00000000000000";

  private static final Log _log = LogFactoryUtil.getLog(LayoutTypePortletImpl.class);

  private boolean _customizedView;
  private final Format _dateFormat =
      FastDateFormatFactoryUtil.getSimpleDateFormat(PropsValues.INDEX_DATE_FORMAT_PATTERN);
  private transient List<Portlet> _embeddedPortlets;
  private boolean _enablePortletLayoutListener = true;
  private Layout _layoutSetPrototypeLayout;
  private PortalPreferences _portalPreferences;
  private boolean _updatePermission;
}
  private void _doServeResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    HttpServletRequest ownerLayoutRequest = getOwnerLayoutRequestWrapper(request, portlet);

    Layout ownerLayout = (Layout) ownerLayoutRequest.getAttribute(WebKeys.LAYOUT);

    boolean allowAddPortletDefaultResource =
        PortalUtil.isAllowAddPortletDefaultResource(ownerLayoutRequest, portlet);

    if (!allowAddPortletDefaultResource) {
      String url = null;

      LastPath lastPath = (LastPath) request.getAttribute(WebKeys.LAST_PATH);

      if (lastPath != null) {
        StringBundler sb = new StringBundler(3);

        sb.append(PortalUtil.getPortalURL(request));
        sb.append(lastPath.getContextPath());
        sb.append(lastPath.getPath());

        url = sb.toString();
      } else {
        url = String.valueOf(request.getRequestURI());
      }

      response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      _log.error("Reject serveResource for " + url + " on " + portlet.getPortletId());

      return;
    }

    WindowState windowState = (WindowState) request.getAttribute(WebKeys.WINDOW_STATE);

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    String portletPrimaryKey =
        PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId());

    portletDisplay.setId(portlet.getPortletId());
    portletDisplay.setRootPortletId(portlet.getRootPortletId());
    portletDisplay.setInstanceId(portlet.getInstanceId());
    portletDisplay.setResourcePK(portletPrimaryKey);
    portletDisplay.setPortletName(portletConfig.getPortletName());
    portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portlet.getPortletId()));

    WebDAVStorage webDAVStorage = portlet.getWebDAVStorageInstance();

    if (webDAVStorage != null) {
      portletDisplay.setWebDAVEnabled(true);
    } else {
      portletDisplay.setWebDAVEnabled(false);
    }

    ResourceRequestImpl resourceRequestImpl =
        ResourceRequestFactory.create(
            request,
            portlet,
            invokerPortlet,
            portletContext,
            windowState,
            portletMode,
            portletPreferences,
            layout.getPlid());

    long companyId = PortalUtil.getCompanyId(request);

    ResourceResponseImpl resourceResponseImpl =
        ResourceResponseFactory.create(
            resourceRequestImpl, response, portlet.getPortletId(), companyId);

    resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

    try {
      ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      long scopeGroupId = themeDisplay.getScopeGroupId();

      boolean access =
          PortletPermissionUtil.hasAccessPermission(
              permissionChecker, scopeGroupId, ownerLayout, portlet, portletMode);

      if (access) {
        invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);

        resourceResponseImpl.transferHeaders(response);
      }
    } finally {
      ServiceContextThreadLocal.popServiceContext();
    }
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    FileEntry fileEntry = null;

    PortletConfig portletConfig = getPortletConfig(actionRequest);

    try {
      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }

        throw new PortalException(uploadException.getCause());
      } else if (cmd.equals(Constants.ADD)
          || cmd.equals(Constants.ADD_DYNAMIC)
          || cmd.equals(Constants.UPDATE)
          || cmd.equals(Constants.UPDATE_AND_CHECKIN)) {

        fileEntry = updateFileEntry(portletConfig, actionRequest, actionResponse);
      } else if (cmd.equals(Constants.ADD_MULTIPLE)) {
        addMultipleFileEntries(portletConfig, actionRequest, actionResponse);

        hideDefaultSuccessMessage(actionRequest);
      } else if (cmd.equals(Constants.ADD_TEMP)) {
        addTempFileEntry(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteFileEntry(actionRequest, false);
      } else if (cmd.equals(Constants.DELETE_TEMP)) {
        deleteTempFileEntry(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.CANCEL_CHECKOUT)) {
        cancelFileEntriesCheckOut(actionRequest);
      } else if (cmd.equals(Constants.CHECKIN)) {
        checkInFileEntries(actionRequest);
      } else if (cmd.equals(Constants.CHECKOUT)) {
        checkOutFileEntries(actionRequest);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteFileEntry(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      } else if (cmd.equals(Constants.REVERT)) {
        revertFileEntry(actionRequest);
      }

      WindowState windowState = actionRequest.getWindowState();

      if (cmd.equals(Constants.ADD_TEMP) || cmd.equals(Constants.DELETE_TEMP)) {

        actionResponse.setRenderParameter("mvcPath", "/null.jsp");
      } else if (cmd.equals(Constants.PREVIEW)) {
      } else if (!windowState.equals(LiferayWindowState.POP_UP)) {
      } else {
        String redirect = ParamUtil.getString(actionRequest, "redirect");
        int workflowAction =
            ParamUtil.getInteger(
                actionRequest, "workflowAction", WorkflowConstants.ACTION_SAVE_DRAFT);

        if ((fileEntry != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

          redirect = getSaveAndContinueRedirect(portletConfig, actionRequest, fileEntry, redirect);

          sendRedirect(actionRequest, actionResponse, redirect);
        } else {
          if (windowState.equals(LiferayWindowState.POP_UP)) {
            redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

            if (Validator.isNotNull(redirect)) {
              if (cmd.equals(Constants.ADD) && (fileEntry != null)) {

                String portletId = HttpUtil.getParameter(redirect, "p_p_id", false);

                String namespace = PortalUtil.getPortletNamespace(portletId);

                redirect =
                    HttpUtil.addParameter(
                        redirect, namespace + "className", DLFileEntry.class.getName());
                redirect =
                    HttpUtil.addParameter(
                        redirect, namespace + "classPK", fileEntry.getFileEntryId());
              }

              sendRedirect(actionRequest, actionResponse, redirect);
            }
          }
        }
      }
    } catch (Exception e) {
      handleUploadException(portletConfig, actionRequest, actionResponse, cmd, e);
    }
  }