@Override
  public PortletURL getURLAdd(
      LiferayPortletRequest liferayPortletRequest,
      LiferayPortletResponse liferayPortletResponse,
      long classTypeId)
      throws PortalException {

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

    CalendarResource calendarResource =
        CalendarResourceUtil.getScopeGroupCalendarResource(
            liferayPortletRequest, themeDisplay.getScopeGroupId());

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

    PortletURL portletURL =
        PortalUtil.getControlPanelPortletURL(
            liferayPortletRequest, CalendarPortletKeys.CALENDAR, PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcPath", "/edit_calendar_booking.jsp");

    Calendar calendar = calendarResource.getDefaultCalendar();

    portletURL.setParameter("calendarId", String.valueOf(calendar.getCalendarId()));

    return portletURL;
  }
  protected void deleteImages(ActionRequest actionRequest) throws Exception {
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long[] deleteFileEntryIds = null;

    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");

    if (fileEntryId > 0) {
      deleteFileEntryIds = new long[] {fileEntryId};
    } else {
      deleteFileEntryIds =
          StringUtil.split(ParamUtil.getString(actionRequest, "deleteFileEntryIds"), 0L);
    }

    Folder folder =
        _blogsEntryLocalService.addAttachmentsFolder(
            themeDisplay.getUserId(), themeDisplay.getScopeGroupId());

    for (long deleteFileEntryId : deleteFileEntryIds) {
      FileEntry fileEntry = PortletFileRepositoryUtil.getPortletFileEntry(deleteFileEntryId);

      if (fileEntry.getFolderId() != folder.getFolderId()) {
        continue;
      }

      if ((fileEntry.getUserId() == themeDisplay.getUserId())
          || BlogsPermission.contains(
              themeDisplay.getPermissionChecker(),
              themeDisplay.getScopeGroupId(),
              ActionKeys.UPDATE)) {

        PortletFileRepositoryUtil.deletePortletFileEntry(deleteFileEntryId);
      }
    }
  }
Example #3
0
  @Override
  public PortletURL getViewContentURL(HttpServletRequest request, String className, long classPK)
      throws PortalException {

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

    String portletId =
        PortletProviderUtil.getPortletId(TrashEntry.class.getName(), PortletProvider.Action.VIEW);

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

      return null;
    }

    TrashHandler trashHandler = TrashHandlerRegistryUtil.getTrashHandler(className);

    if (trashHandler.isInTrashContainer(classPK)) {
      TrashEntry trashEntry = trashHandler.getTrashEntry(classPK);

      className = trashEntry.getClassName();
      classPK = trashEntry.getClassPK();

      trashHandler = TrashHandlerRegistryUtil.getTrashHandler(className);
    }

    TrashRenderer trashRenderer = trashHandler.getTrashRenderer(classPK);

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

    PortletURL portletURL =
        PortalUtil.getControlPanelPortletURL(request, portletId, PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcPath", "/view_content.jsp");
    portletURL.setParameter("redirect", themeDisplay.getURLCurrent());

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

    if (trashEntry.getRootEntry() != null) {
      portletURL.setParameter("className", className);
      portletURL.setParameter("classPK", String.valueOf(classPK));
    } else {
      portletURL.setParameter("trashEntryId", String.valueOf(trashEntry.getEntryId()));
    }

    portletURL.setParameter("showAssetMetadata", Boolean.TRUE.toString());

    return portletURL;
  }
  public AssetEntryQuery(long[] classNameIds, SearchContainer<?> searchContainer) {

    this();

    setClassNameIds(classNameIds);
    _start = searchContainer.getStart();
    _end = searchContainer.getEnd();

    if (Validator.isNotNull(searchContainer.getOrderByCol())) {
      setOrderByCol1(searchContainer.getOrderByCol());
      setOrderByType1(searchContainer.getOrderByType());
    }

    PortletRequest portletRequest = searchContainer.getPortletRequest();

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

    _groupIds = new long[] {themeDisplay.getScopeGroupId()};

    long categoryId = ParamUtil.getLong(portletRequest, "categoryId");

    if (categoryId > 0) {
      _allCategoryIds = new long[] {categoryId};
    }

    String tagName = ParamUtil.getString(portletRequest, "tag");

    if (Validator.isNotNull(tagName)) {
      _allTagIds =
          AssetTagLocalServiceUtil.getTagIds(themeDisplay.getSiteGroupId(), new String[] {tagName});

      _allTagIdsArray = new long[][] {_allTagIds};
    }
  }
  protected JournalArticle getArticle(HttpServletRequest request) {
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    long groupId = ParamUtil.getLong(request, "groupId", themeDisplay.getScopeGroupId());
    long classNameId = ParamUtil.getLong(request, "classNameId");
    long classPK = ParamUtil.getLong(request, "classPK");
    String articleId = ParamUtil.getString(request, "articleId");
    int status = ParamUtil.getInteger(request, "status", WorkflowConstants.STATUS_ANY);

    JournalArticle article = null;

    if (Validator.isNotNull(articleId)) {
      article = _journalArticleLocalService.fetchLatestArticle(groupId, articleId, status);
    } else if ((classNameId > 0) && (classPK > JournalArticleConstants.CLASSNAME_ID_DEFAULT)) {

      String className = PortalUtil.getClassName(classNameId);

      try {
        article = _journalArticleLocalService.getLatestArticle(groupId, className, classPK);
      } catch (PortalException pe) {
        return null;
      }
    }

    return article;
  }
  protected void checkEditPermissionsJSP(PortletRequest request) throws PortalException {

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

    String modelResource = ParamUtil.getString(request, "modelResource");

    long resourceGroupId =
        ParamUtil.getLong(request, "resourceGroupId", themeDisplay.getScopeGroupId());

    if (Validator.isNotNull(modelResource)) {
      String resourcePrimKey = ParamUtil.getString(request, "resourcePrimKey");

      _permissionService.checkPermission(resourceGroupId, modelResource, resourcePrimKey);

      return;
    }

    String portletResource = ParamUtil.getString(request, "portletResource");

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    Layout layout = PortletConfigurationLayoutUtil.getLayout(themeDisplay);

    _portletPermission.check(
        permissionChecker, resourceGroupId, layout, portletResource, ActionKeys.PERMISSIONS);
  }
  public List<ManagementBarFilterItem> getManagementBarStatusFilterItems()
      throws PortalException, PortletException {

    List<ManagementBarFilterItem> managementBarFilterItems = new ArrayList<>();

    managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_ANY));
    managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_DRAFT));

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

    int workflowDefinitionLinksCount =
        WorkflowDefinitionLinkLocalServiceUtil.getWorkflowDefinitionLinksCount(
            themeDisplay.getCompanyId(),
            themeDisplay.getScopeGroupId(),
            JournalFolder.class.getName());

    if (workflowDefinitionLinksCount > 0) {
      managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_PENDING));
      managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_DENIED));
    }

    managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_SCHEDULED));
    managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_APPROVED));
    managementBarFilterItems.add(getManagementBarFilterItem(WorkflowConstants.STATUS_EXPIRED));

    return managementBarFilterItems;
  }
  @Override
  public String getURL(PortletRequest portletRequest, PortletResponse portletResponse) {

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

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Portlet portlet = _portletLocalService.getPortletById(portletDisplay.getId());

    PortletURL portletURL =
        PortletURLFactoryUtil.create(
            portletRequest,
            PortletProviderUtil.getPortletId(
                DDMStructure.class.getName(), PortletProvider.Action.VIEW),
            PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcPath", "/view.jsp");
    portletURL.setParameter("backURL", themeDisplay.getURLCurrent());
    portletURL.setParameter("groupId", String.valueOf(themeDisplay.getScopeGroupId()));
    portletURL.setParameter("refererPortletName", DLPortletKeys.DOCUMENT_LIBRARY);
    portletURL.setParameter("refererWebDAVToken", WebDAVUtil.getStorageToken(portlet));
    portletURL.setParameter("showAncestorScopes", Boolean.TRUE.toString());
    portletURL.setParameter("showManageTemplates", Boolean.FALSE.toString());

    return portletURL.toString();
  }
  protected void deleteCategories(ActionRequest actionRequest, boolean moveToTrash)
      throws Exception {

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

    long[] deleteCategoryIds = null;

    long categoryId = ParamUtil.getLong(actionRequest, "mbCategoryId");

    if (categoryId > 0) {
      deleteCategoryIds = new long[] {categoryId};
    } else {
      deleteCategoryIds =
          StringUtil.split(ParamUtil.getString(actionRequest, "deleteCategoryIds"), 0L);
    }

    List<TrashedModel> trashedModels = new ArrayList<>();

    for (long deleteCategoryId : deleteCategoryIds) {
      if (moveToTrash) {
        MBCategory category = _mbCategoryService.moveCategoryToTrash(deleteCategoryId);

        trashedModels.add(category);
      } else {
        _mbCategoryService.deleteCategory(themeDisplay.getScopeGroupId(), deleteCategoryId);
      }
    }

    if (moveToTrash && !trashedModels.isEmpty()) {
      TrashUtil.addTrashSessionMessages(actionRequest, trashedModels);

      hideDefaultSuccessMessage(actionRequest);
    }
  }
  protected void unsubscribeFolder(ActionRequest actionRequest) throws Exception {

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

    long folderId = ParamUtil.getLong(actionRequest, "folderId");

    _bookmarksFolderService.unsubscribeFolder(themeDisplay.getScopeGroupId(), folderId);
  }
  protected void unsubscribeCategory(ActionRequest actionRequest) throws Exception {

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

    long categoryId = ParamUtil.getLong(actionRequest, "mbCategoryId");

    _mbCategoryService.unsubscribeCategory(themeDisplay.getScopeGroupId(), categoryId);
  }
  protected long getDisplayStyleGroupId() {
    if (_ddmTemplateGroupId > 0) {
      return _ddmTemplateGroupId;
    }

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

    return themeDisplay.getScopeGroupId();
  }
  @Override
  public boolean isShow(PortletRequest portletRequest) {
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    return ShoppingPermission.contains(
        themeDisplay.getPermissionChecker(),
        themeDisplay.getScopeGroupId(),
        ActionKeys.PERMISSIONS);
  }
  public FeedSearchTerms(PortletRequest portletRequest) {
    super(portletRequest);

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

    description = ParamUtil.getString(portletRequest, DESCRIPTION);
    feedId = ParamUtil.getString(portletRequest, FEED_ID);
    groupId = ParamUtil.getLong(portletRequest, GROUP_ID, themeDisplay.getScopeGroupId());
    name = ParamUtil.getString(portletRequest, NAME);
  }
Example #15
0
  public long[] getGroupIds() {
    if (_groupIds == null) {
      ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

      _groupIds =
          AssetPublisherUtil.getGroupIds(
              _portletPreferences, themeDisplay.getScopeGroupId(), themeDisplay.getLayout());
    }

    return _groupIds;
  }
Example #16
0
  public Long getScopeGroupId() {
    if (_scopeGroupId != null) {
      return _scopeGroupId;
    }

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

    _scopeGroupId = themeDisplay.getScopeGroupId();

    return _scopeGroupId;
  }
Example #17
0
  public long getDisplayStyleGroupId() {
    if (_displayStyleGroupId == null) {
      ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

      _displayStyleGroupId =
          GetterUtil.getLong(
              _portletPreferences.getValue("displayStyleGroupId", null),
              themeDisplay.getScopeGroupId());
    }

    return _displayStyleGroupId;
  }
Example #18
0
  @Override
  public PortletURL getViewURL(HttpServletRequest request) throws PortalException {

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

    String portletId =
        PortletProviderUtil.getPortletId(TrashEntry.class.getName(), PortletProvider.Action.VIEW);

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

      return null;
    }

    PortletURL portletURL =
        PortalUtil.getControlPanelPortletURL(request, portletId, PortletRequest.RENDER_PHASE);

    portletURL.setParameter("redirect", themeDisplay.getURLCurrent());

    return portletURL;
  }
  @Override
  public boolean isShow(PortletRequest portletRequest) {
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    try {
      MBMessage message = ActionUtil.getMessage(portletRequest);

      return MBCategoryPermission.contains(
          themeDisplay.getPermissionChecker(),
          themeDisplay.getScopeGroupId(),
          message.getCategoryId(),
          ActionKeys.LOCK_THREAD);
    } catch (Exception e) {
    }

    return false;
  }
  @Override
  protected boolean isProcessPortletRequest(PortletRequest portletRequest) {
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    if (permissionChecker.isCompanyAdmin()) {
      return true;
    }

    Group group = themeDisplay.getScopeGroup();

    if (group.isSite() && permissionChecker.isGroupAdmin(themeDisplay.getScopeGroupId())) {

      return true;
    }

    return false;
  }
  protected List<SocialActivity> getSocialActivities(ResourceRequest resourceRequest, int max)
      throws Exception {

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

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    int start = 0;

    if (group.isOrganization()) {
      return _socialActivityLocalService.getOrganizationActivities(
          group.getOrganizationId(), start, max);
    } else if (group.isRegularSite()) {
      return _socialActivityLocalService.getGroupActivities(group.getGroupId(), start, max);
    } else if (group.isUser()) {
      return _socialActivityLocalService.getUserActivities(group.getClassPK(), start, max);
    }

    return Collections.emptyList();
  }
  @Override
  public boolean isShow(PortletRequest portletRequest) {
    try {
      MBCategory category = ActionUtil.getCategory(portletRequest);

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

      if (MBCategoryPermission.contains(
          themeDisplay.getPermissionChecker(),
          themeDisplay.getScopeGroupId(),
          getCategoryId(category),
          ActionKeys.MOVE_THREAD)) {

        return true;
      }
    } catch (Exception e) {
    }

    return false;
  }
  public int getStatus() {
    if (_status != null) {
      return _status;
    }

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

    int defaultStatus = WorkflowConstants.STATUS_APPROVED;

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    if (permissionChecker.isContentReviewer(
            themeDisplay.getCompanyId(), themeDisplay.getScopeGroupId())
        || isNavigationMine()) {

      defaultStatus = WorkflowConstants.STATUS_ANY;
    }

    _status = ParamUtil.getInteger(_request, "status", defaultStatus);

    return _status;
  }
  @Override
  public String getURL(PortletRequest portletRequest, PortletResponse portletResponse) {

    String url = StringPool.BLANK;

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

    try {
      url =
          PermissionsURLTag.doTag(
              StringPool.BLANK,
              "com.liferay.shopping",
              themeDisplay.getScopeGroupName(),
              null,
              String.valueOf(themeDisplay.getScopeGroupId()),
              LiferayWindowState.POP_UP.toString(),
              null,
              themeDisplay.getRequest());
    } catch (Exception e) {
    }

    return url;
  }
  public void updateRolePermissions(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    String portletResource = ParamUtil.getString(actionRequest, "portletResource");
    String modelResource = ParamUtil.getString(actionRequest, "modelResource");
    long[] roleIds =
        StringUtil.split(ParamUtil.getString(actionRequest, "rolesSearchContainerPrimaryKeys"), 0L);

    String selResource = PortletConstants.getRootPortletId(portletResource);

    if (Validator.isNotNull(modelResource)) {
      selResource = modelResource;
    }

    long resourceGroupId =
        ParamUtil.getLong(actionRequest, "resourceGroupId", themeDisplay.getScopeGroupId());
    String resourcePrimKey = ParamUtil.getString(actionRequest, "resourcePrimKey");

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

    if (_resourceBlockLocalService.isSupported(selResource)) {
      for (long roleId : roleIds) {
        List<String> actionIds = getActionIdsList(actionRequest, roleId, true);

        roleIdsToActionIds.put(roleId, actionIds.toArray(new String[actionIds.size()]));
      }

      _resourceBlockService.setIndividualScopePermissions(
          themeDisplay.getCompanyId(),
          resourceGroupId,
          selResource,
          GetterUtil.getLong(resourcePrimKey),
          roleIdsToActionIds);
    } else {
      for (long roleId : roleIds) {
        String[] actionIds = getActionIds(actionRequest, roleId, false);

        roleIdsToActionIds.put(roleId, actionIds);
      }

      _resourcePermissionService.setIndividualResourcePermissions(
          resourceGroupId,
          themeDisplay.getCompanyId(),
          selResource,
          resourcePrimKey,
          roleIdsToActionIds);
    }

    if (PropsValues.PERMISSIONS_PROPAGATION_ENABLED) {
      Portlet portlet =
          _portletLocalService.getPortletById(themeDisplay.getCompanyId(), portletResource);

      PermissionPropagator permissionPropagator = portlet.getPermissionPropagatorInstance();

      if (permissionPropagator != null) {
        permissionPropagator.propagateRolePermissions(
            actionRequest, modelResource, resourcePrimKey, roleIds);
      }
    }

    if (Validator.isNull(modelResource)) {

      // Force update of layout modified date. See LPS-59246.

      Portlet portlet = ActionUtil.getPortlet(actionRequest);

      PortletPreferences portletPreferences =
          ActionUtil.getLayoutPortletSetup(actionRequest, portlet);

      portletPreferences.store();
    }
  }
Example #26
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, Object> contextObjects,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      Document document,
      PortletRequestModel portletRequestModel,
      String script,
      String langType,
      boolean propagateException)
      throws Exception {

    // Setup listeners

    if (_log.isDebugEnabled()) {
      _log.debug("Language " + languageId);
    }

    if (Validator.isNull(viewMode)) {
      viewMode = Constants.VIEW;
    }

    if (_logTokens.isDebugEnabled()) {
      String tokensString = PropertiesUtil.list(tokens);

      _logTokens.debug(tokensString);
    }

    if (_logTransformBefore.isDebugEnabled()) {
      _logTransformBefore.debug(document);
    }

    List<TransformerListener> transformerListeners =
        JournalTransformerListenerRegistryUtil.getTransformerListeners();

    for (TransformerListener transformerListener : transformerListeners) {

      // Modify XML

      if (_logXmlBeforeListener.isDebugEnabled()) {
        _logXmlBeforeListener.debug(document);
      }

      if (transformerListener != null) {
        document = transformerListener.onXml(document, languageId, tokens);

        if (_logXmlAfterListener.isDebugEnabled()) {
          _logXmlAfterListener.debug(document);
        }
      }

      // Modify script

      if (_logScriptBeforeListener.isDebugEnabled()) {
        _logScriptBeforeListener.debug(script);
      }

      if (transformerListener != null) {
        script = transformerListener.onScript(script, document, languageId, tokens);

        if (_logScriptAfterListener.isDebugEnabled()) {
          _logScriptAfterListener.debug(script);
        }
      }
    }

    // Transform

    String output = null;

    if (Validator.isNull(langType)) {
      output = LocalizationUtil.getLocalization(document.asXML(), languageId);
    } else {
      long companyId = 0;
      long companyGroupId = 0;
      long articleGroupId = 0;
      long classNameId = 0;

      if (tokens != null) {
        companyId = GetterUtil.getLong(tokens.get("company_id"));
        companyGroupId = GetterUtil.getLong(tokens.get("company_group_id"));
        articleGroupId = GetterUtil.getLong(tokens.get("article_group_id"));
        classNameId = GetterUtil.getLong(tokens.get(TemplateConstants.CLASS_NAME_ID));
      }

      long scopeGroupId = 0;
      long siteGroupId = 0;

      if (themeDisplay != null) {
        companyId = themeDisplay.getCompanyId();
        companyGroupId = themeDisplay.getCompanyGroupId();
        scopeGroupId = themeDisplay.getScopeGroupId();
        siteGroupId = themeDisplay.getSiteGroupId();
      }

      String templateId = tokens.get("template_id");

      templateId = getTemplateId(templateId, companyId, companyGroupId, articleGroupId);

      Template template = getTemplate(templateId, tokens, languageId, document, script, langType);

      if (contextObjects != null) {
        template.putAll(contextObjects);
      }

      UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

      try {
        if (document != null) {
          Element rootElement = document.getRootElement();

          List<TemplateNode> templateNodes =
              getTemplateNodes(
                  themeDisplay, rootElement, Long.valueOf(tokens.get("ddm_structure_id")));

          if (templateNodes != null) {
            for (TemplateNode templateNode : templateNodes) {
              template.put(templateNode.getName(), templateNode);
            }
          }

          if (portletRequestModel != null) {
            template.put("request", portletRequestModel.toMap());

            if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
              Document requestDocument = SAXReaderUtil.read(portletRequestModel.toXML());

              Element requestElement = requestDocument.getRootElement();

              template.put("xmlRequest", requestElement.asXML());
            }
          } else {
            Element requestElement = rootElement.element("request");

            template.put("request", insertRequestVariables(requestElement));

            if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
              template.put("xmlRequest", requestElement.asXML());
            }
          }
        }

        template.put("articleGroupId", articleGroupId);
        template.put("company", getCompany(themeDisplay, companyId));
        template.put("companyId", companyId);
        template.put("device", getDevice(themeDisplay));

        String templatesPath = getTemplatesPath(companyId, articleGroupId, classNameId);

        Locale locale = LocaleUtil.fromLanguageId(languageId);

        template.put("locale", locale);

        template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
        template.put("randomNamespace", StringUtil.randomId() + StringPool.UNDERLINE);
        template.put("scopeGroupId", scopeGroupId);
        template.put("siteGroupId", siteGroupId);
        template.put("templatesPath", templatesPath);
        template.put("viewMode", viewMode);

        if (themeDisplay != null) {
          TemplateManager templateManager = TemplateManagerUtil.getTemplateManager(langType);

          HttpServletRequest request = themeDisplay.getRequest();

          templateManager.addTaglibSupport(template, request, themeDisplay.getResponse());
          templateManager.addTaglibTheme(
              template,
              "taglibLiferay",
              request,
              new PipingServletResponse(themeDisplay.getResponse(), unsyncStringWriter));
        }

        // Deprecated variables

        template.put("groupId", articleGroupId);
        template.put("journalTemplatesPath", templatesPath);

        mergeTemplate(template, unsyncStringWriter, propagateException);
      } catch (Exception e) {
        if (e instanceof DocumentException) {
          throw new TransformException("Unable to read XML document", e);
        } else if (e instanceof IOException) {
          throw new TransformException("Error reading template", e);
        } else if (e instanceof TransformException) {
          throw (TransformException) e;
        } else {
          throw new TransformException("Unhandled exception", e);
        }
      }

      output = unsyncStringWriter.toString();
    }

    // Postprocess output

    for (TransformerListener transformerListener : transformerListeners) {

      // Modify output

      if (_logOutputBeforeListener.isDebugEnabled()) {
        _logOutputBeforeListener.debug(output);
      }

      output = transformerListener.onOutput(output, languageId, tokens);

      if (_logOutputAfterListener.isDebugEnabled()) {
        _logOutputAfterListener.debug(output);
      }
    }

    if (_logTransfromAfter.isDebugEnabled()) {
      _logTransfromAfter.debug(output);
    }

    return output;
  }
  @Override
  public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {

    try {

      // Do not randomize look and feel unless the user is logged in

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

      if (!themeDisplay.isSignedIn()) {
        return;
      }

      // Do not randomize look and feel unless the user is accessing the
      // portal

      String requestURI = GetterUtil.getString(request.getRequestURI());

      if (!requestURI.endsWith("/portal/layout")) {
        return;
      }

      // Do not randomize look and feel unless the user is accessing a
      // personal layout

      Layout layout = themeDisplay.getLayout();

      if (layout == null) {
        return;
      }

      boolean wapTheme = BrowserSnifferUtil.isWap(request);

      List<Theme> themes =
          ThemeLocalServiceUtil.getPageThemes(
              themeDisplay.getCompanyId(),
              themeDisplay.getScopeGroupId(),
              themeDisplay.getUserId(),
              wapTheme);

      if (!themes.isEmpty()) {
        Theme theme = themes.get(RandomUtil.nextInt(themes.size()));

        List<ColorScheme> colorSchemes = theme.getColorSchemes();

        ColorScheme colorScheme = colorSchemes.get(RandomUtil.nextInt(colorSchemes.size()));

        LayoutServiceUtil.updateLookAndFeel(
            layout.getGroupId(),
            layout.isPrivateLayout(),
            layout.getPlid(),
            theme.getThemeId(),
            colorScheme.getColorSchemeId(),
            layout.getCss(),
            wapTheme);

        themeDisplay.setLookAndFeel(theme, colorScheme);

        request.setAttribute(WebKeys.THEME, theme);
        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
      }
    } catch (Exception e) {
      _log.error(e, e);

      throw new ActionException(e);
    }
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    Company company = themeDisplay.getCompany();

    if (!company.isStrangers()) {
      throw new PrincipalException.MustBeEnabled(
          company.getCompanyId(), PropsKeys.COMPANY_SECURITY_STRANGERS);
    }

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

    try {
      if (cmd.equals(Constants.ADD)) {
        if (PropsValues.CAPTCHA_CHECK_PORTAL_CREATE_ACCOUNT) {
          CaptchaUtil.check(actionRequest);
        }

        addUser(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.RESET)) {
        resetUser(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.UPDATE)) {
        updateIncompleteUser(actionRequest, actionResponse);
      }
    } catch (Exception e) {
      if (e instanceof UserEmailAddressException.MustNotBeDuplicate
          || e instanceof UserScreenNameException.MustNotBeDuplicate) {

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

        User user =
            _userLocalService.fetchUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);

        if ((user == null) || (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE)) {

          SessionErrors.add(actionRequest, e.getClass(), e);
        } else {
          actionResponse.setRenderParameter("mvcPath", "/update_account.jsp");
        }
      } else if (e instanceof AddressCityException
          || e instanceof AddressStreetException
          || e instanceof AddressZipException
          || e instanceof CaptchaConfigurationException
          || e instanceof CaptchaTextException
          || e instanceof CompanyMaxUsersException
          || e instanceof ContactBirthdayException
          || e instanceof ContactNameException
          || e instanceof DuplicateOpenIdException
          || e instanceof EmailAddressException
          || e instanceof GroupFriendlyURLException
          || e instanceof NoSuchCountryException
          || e instanceof NoSuchListTypeException
          || e instanceof NoSuchOrganizationException
          || e instanceof NoSuchRegionException
          || e instanceof OrganizationParentException
          || e instanceof PhoneNumberException
          || e instanceof RequiredFieldException
          || e instanceof RequiredUserException
          || e instanceof TermsOfUseException
          || e instanceof UserEmailAddressException
          || e instanceof UserIdException
          || e instanceof UserPasswordException
          || e instanceof UserScreenNameException
          || e instanceof UserSmsException
          || e instanceof WebsiteURLException) {

        SessionErrors.add(actionRequest, e.getClass(), e);
      } else {
        throw e;
      }
    }

    if (Validator.isNull(PropsValues.COMPANY_SECURITY_STRANGERS_URL)) {
      return;
    }

    try {
      Layout layout =
          _layoutLocalService.getFriendlyURLLayout(
              themeDisplay.getScopeGroupId(), false, PropsValues.COMPANY_SECURITY_STRANGERS_URL);

      String redirect = PortalUtil.getLayoutURL(layout, themeDisplay);

      sendRedirect(actionRequest, actionResponse, redirect);
    } catch (NoSuchLayoutException nsle) {
    }
  }
  protected MBMessage updateMessage(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    long messageId = ParamUtil.getLong(actionRequest, "messageId");

    long groupId = themeDisplay.getScopeGroupId();
    long categoryId = ParamUtil.getLong(actionRequest, "mbCategoryId");
    long threadId = ParamUtil.getLong(actionRequest, "threadId");
    long parentMessageId = ParamUtil.getLong(actionRequest, "parentMessageId");
    String subject = ParamUtil.getString(actionRequest, "subject");
    String body = ParamUtil.getString(actionRequest, "body");

    MBGroupServiceSettings mbGroupServiceSettings = MBGroupServiceSettings.getInstance(groupId);

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs = new ArrayList<>(5);

    try {
      UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

      for (int i = 1; i <= 5; i++) {
        String fileName = uploadPortletRequest.getFileName("msgFile" + i);
        InputStream inputStream = uploadPortletRequest.getFileAsStream("msgFile" + i);

        if ((inputStream == null) || Validator.isNull(fileName)) {
          continue;
        }

        ObjectValuePair<String, InputStream> inputStreamOVP =
            new ObjectValuePair<>(fileName, inputStream);

        inputStreamOVPs.add(inputStreamOVP);
      }

      boolean question = ParamUtil.getBoolean(actionRequest, "question");
      boolean anonymous = ParamUtil.getBoolean(actionRequest, "anonymous");
      double priority = ParamUtil.getDouble(actionRequest, "priority");
      boolean allowPingbacks = ParamUtil.getBoolean(actionRequest, "allowPingbacks");

      ServiceContext serviceContext =
          ServiceContextFactory.getInstance(MBMessage.class.getName(), actionRequest);

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

      serviceContext.setAttribute("preview", preview);

      MBMessage message = null;

      if (messageId <= 0) {
        if (PropsValues.CAPTCHA_CHECK_PORTLET_MESSAGE_BOARDS_EDIT_MESSAGE) {

          CaptchaUtil.check(actionRequest);
        }

        if (threadId <= 0) {

          // Post new thread

          message =
              _mbMessageService.addMessage(
                  groupId,
                  categoryId,
                  subject,
                  body,
                  mbGroupServiceSettings.getMessageFormat(),
                  inputStreamOVPs,
                  anonymous,
                  priority,
                  allowPingbacks,
                  serviceContext);

          if (question) {
            _mbThreadLocalService.updateQuestion(message.getThreadId(), true);
          }
        } else {

          // Post reply

          message =
              _mbMessageService.addMessage(
                  parentMessageId,
                  subject,
                  body,
                  mbGroupServiceSettings.getMessageFormat(),
                  inputStreamOVPs,
                  anonymous,
                  priority,
                  allowPingbacks,
                  serviceContext);
        }
      } else {
        List<String> existingFiles = new ArrayList<>();

        for (int i = 1; i <= 5; i++) {
          String path = ParamUtil.getString(actionRequest, "existingPath" + i);

          if (Validator.isNotNull(path)) {
            existingFiles.add(path);
          }
        }

        // Update message

        message =
            _mbMessageService.updateMessage(
                messageId,
                subject,
                body,
                inputStreamOVPs,
                existingFiles,
                priority,
                allowPingbacks,
                serviceContext);

        if (message.isRoot()) {
          _mbThreadLocalService.updateQuestion(message.getThreadId(), question);
        }
      }

      PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

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

      if (!preview
          && subscribe
          && MBMessagePermission.contains(permissionChecker, message, ActionKeys.SUBSCRIBE)) {

        _mbMessageService.subscribeMessage(message.getMessageId());
      }

      return message;
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  public ArticleSearch getSearchContainer() throws PortalException {
    ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

    ArticleSearch articleSearchContainer =
        new ArticleSearch(_liferayPortletRequest, getPortletURL());

    OrderByComparator<JournalArticle> orderByComparator =
        JournalPortletUtil.getArticleOrderByComparator(getOrderByCol(), getOrderByType());

    articleSearchContainer.setOrderByCol(getOrderByCol());
    articleSearchContainer.setOrderByComparator(orderByComparator);
    articleSearchContainer.setOrderByType(getOrderByType());

    EntriesChecker entriesChecker =
        new EntriesChecker(_liferayPortletRequest, _liferayPortletResponse);

    entriesChecker.setCssClass("entry-selector");

    articleSearchContainer.setRowChecker(entriesChecker);

    EntriesMover entriesMover = new EntriesMover(themeDisplay.getScopeGroupId());

    articleSearchContainer.setRowMover(entriesMover);

    if (isNavigationMine() || isNavigationRecent()) {
      boolean includeOwner = true;

      if (isNavigationMine()) {
        includeOwner = false;
      }

      if (isNavigationRecent()) {
        articleSearchContainer.setOrderByCol("create-date");
        articleSearchContainer.setOrderByType(getOrderByType());
      }

      int total =
          JournalArticleServiceUtil.getGroupArticlesCount(
              themeDisplay.getScopeGroupId(),
              themeDisplay.getUserId(),
              getFolderId(),
              getStatus(),
              includeOwner);

      articleSearchContainer.setTotal(total);

      List results =
          JournalArticleServiceUtil.getGroupArticles(
              themeDisplay.getScopeGroupId(),
              themeDisplay.getUserId(),
              getFolderId(),
              getStatus(),
              includeOwner,
              articleSearchContainer.getStart(),
              articleSearchContainer.getEnd(),
              articleSearchContainer.getOrderByComparator());

      articleSearchContainer.setResults(results);
    } else if (Validator.isNotNull(getDDMStructureKey())) {
      int total =
          JournalArticleServiceUtil.getArticlesCountByStructureId(
              themeDisplay.getScopeGroupId(), getDDMStructureKey(), getStatus());

      articleSearchContainer.setTotal(total);

      List results =
          JournalArticleServiceUtil.getArticlesByStructureId(
              themeDisplay.getScopeGroupId(),
              getDDMStructureKey(),
              getStatus(),
              articleSearchContainer.getStart(),
              articleSearchContainer.getEnd(),
              articleSearchContainer.getOrderByComparator());

      articleSearchContainer.setResults(results);
    } else if (Validator.isNotNull(getDDMTemplateKey())) {
      List<Long> folderIds = new ArrayList<>(1);

      if (getFolderId() != JournalFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

        folderIds.add(getFolderId());
      }

      int total =
          JournalArticleServiceUtil.searchCount(
              themeDisplay.getCompanyId(),
              themeDisplay.getScopeGroupId(),
              folderIds,
              JournalArticleConstants.CLASSNAME_ID_DEFAULT,
              getKeywords(),
              -1.0,
              getDDMStructureKey(),
              getDDMTemplateKey(),
              null,
              null,
              getStatus(),
              null);

      articleSearchContainer.setTotal(total);

      List results =
          JournalArticleServiceUtil.search(
              themeDisplay.getCompanyId(),
              themeDisplay.getScopeGroupId(),
              folderIds,
              JournalArticleConstants.CLASSNAME_ID_DEFAULT,
              getKeywords(),
              -1.0,
              getDDMStructureKey(),
              getDDMTemplateKey(),
              null,
              null,
              getStatus(),
              null,
              articleSearchContainer.getStart(),
              articleSearchContainer.getEnd(),
              articleSearchContainer.getOrderByComparator());

      articleSearchContainer.setResults(results);
    } else if (isSearch()) {
      List<Long> folderIds = new ArrayList<>(1);

      if (getFolderId() != JournalFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

        folderIds.add(getFolderId());
      }

      JournalWebConfiguration journalWebConfiguration =
          (JournalWebConfiguration) _request.getAttribute(JournalWebConfiguration.class.getName());

      if (journalWebConfiguration.journalArticlesSearchWithIndex()) {
        boolean orderByAsc = false;

        if (Validator.equals(getOrderByType(), "asc")) {
          orderByAsc = true;
        }

        Sort sort = null;

        if (Validator.equals(getOrderByCol(), "display-date")) {
          sort = new Sort("displayDate", Sort.LONG_TYPE, orderByAsc);
        } else if (Validator.equals(getOrderByCol(), "modified-date")) {
          sort = new Sort(Field.MODIFIED_DATE, Sort.LONG_TYPE, orderByAsc);
        }

        LinkedHashMap<String, Object> params = new LinkedHashMap<>();

        params.put("expandoAttributes", getKeywords());

        BaseModelSearchResult<JournalArticle> baseModelSearchResult =
            JournalArticleLocalServiceUtil.searchJournalArticles(
                themeDisplay.getCompanyId(),
                themeDisplay.getScopeGroupId(),
                folderIds,
                JournalArticleConstants.CLASSNAME_ID_DEFAULT,
                getDDMStructureKey(),
                getDDMTemplateKey(),
                getKeywords(),
                params,
                articleSearchContainer.getStart(),
                articleSearchContainer.getEnd(),
                sort);

        int total = baseModelSearchResult.getLength();

        articleSearchContainer.setTotal(total);

        List results = baseModelSearchResult.getBaseModels();

        articleSearchContainer.setResults(results);
      } else {
        int total =
            JournalArticleServiceUtil.searchCount(
                themeDisplay.getCompanyId(),
                themeDisplay.getScopeGroupId(),
                folderIds,
                JournalArticleConstants.CLASSNAME_ID_DEFAULT,
                getKeywords(),
                -1.0,
                getDDMStructureKey(),
                getDDMTemplateKey(),
                null,
                null,
                getStatus(),
                null);

        articleSearchContainer.setTotal(total);

        List results =
            JournalArticleServiceUtil.search(
                themeDisplay.getCompanyId(),
                themeDisplay.getScopeGroupId(),
                folderIds,
                JournalArticleConstants.CLASSNAME_ID_DEFAULT,
                getKeywords(),
                -1.0,
                getDDMStructureKey(),
                getDDMTemplateKey(),
                null,
                null,
                getStatus(),
                null,
                articleSearchContainer.getStart(),
                articleSearchContainer.getEnd(),
                articleSearchContainer.getOrderByComparator());

        articleSearchContainer.setResults(results);
      }
    } else {
      int total =
          JournalFolderServiceUtil.getFoldersAndArticlesCount(
              themeDisplay.getScopeGroupId(), 0, getFolderId(), getStatus());

      articleSearchContainer.setTotal(total);

      OrderByComparator<Object> folderOrderByComparator = null;

      boolean orderByAsc = false;

      if (Validator.equals(getOrderByType(), "asc")) {
        orderByAsc = true;
      }

      if (Validator.equals(getOrderByCol(), "display-date")) {
        folderOrderByComparator = new FolderArticleDisplayDateComparator(orderByAsc);
      } else if (Validator.equals(getOrderByCol(), "modified-date")) {
        folderOrderByComparator = new FolderArticleModifiedDateComparator(orderByAsc);
      }

      List results =
          JournalFolderServiceUtil.getFoldersAndArticles(
              themeDisplay.getScopeGroupId(),
              0,
              getFolderId(),
              getStatus(),
              articleSearchContainer.getStart(),
              articleSearchContainer.getEnd(),
              folderOrderByComparator);

      articleSearchContainer.setResults(results);
    }

    return articleSearchContainer;
  }