@Test
  public void testFilterFindByG_N() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();

    addAssetTag(siteGroup.getGroupId(), assetTagName, null);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      try {
        AssetTagFinderUtil.filterFindByG_N(scopeGroup.getGroupId(), assetTagName);

        Assert.fail();
      } catch (NoSuchTagException nste) {
      }

      AssetTag siteGroupAssetTag =
          AssetTagFinderUtil.filterFindByG_N(siteGroup.getGroupId(), assetTagName);

      Assert.assertEquals(StringUtil.toLowerCase(assetTagName), siteGroupAssetTag.getName());
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  @Test(expected = PrincipalException.class)
  public void testCreateRepositoryFromExistingFolderWithoutPermissions() throws Exception {

    DLFolder dlFolder = DLTestUtil.addDLFolder(_group.getGroupId());

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionThreadLocal.setPermissionChecker(new AlwaysDenyingPermissionChecker());

      RepositoryFactoryUtil.create(dlFolder.getFolderId(), 0, 0);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  protected void addModelResources(
      long companyId,
      long groupId,
      long userId,
      String name,
      String primKey,
      String[] groupPermissions,
      String[] guestPermissions,
      PermissionedModel permissionedModel)
      throws PortalException, SystemException {

    if (!PermissionThreadLocal.isAddResource()) {
      return;
    }

    validate(name, false);

    if (primKey == null) {
      return;
    }

    // Individual

    Resource resource = getResource(companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey);

    // Permissions

    boolean flushEnabled = PermissionThreadLocal.isFlushEnabled();

    PermissionThreadLocal.setIndexEnabled(false);

    try {
      addModelResources(
          companyId,
          groupId,
          userId,
          resource,
          groupPermissions,
          guestPermissions,
          permissionedModel);
    } finally {
      PermissionThreadLocal.setIndexEnabled(flushEnabled);

      PermissionCacheUtil.clearCache();

      SearchEngineUtil.updatePermissionFields(name, primKey);
    }
  }
  private static void _populateThreadLocalsFromContext(Map<String, Serializable> context) {

    long companyId = GetterUtil.getLong(context.get("companyId"));

    if (companyId > 0) {
      CompanyThreadLocal.setCompanyId(companyId);
    }

    Locale defaultLocale = (Locale) context.get("defaultLocale");

    if (defaultLocale != null) {
      LocaleThreadLocal.setDefaultLocale(defaultLocale);
    }

    long groupId = GetterUtil.getLong(context.get("groupId"));

    if (groupId > 0) {
      GroupThreadLocal.setGroupId(groupId);
    }

    String principalName = GetterUtil.getString(context.get("principalName"));

    if (Validator.isNotNull(principalName)) {
      PrincipalThreadLocal.setName(principalName);
    }

    PermissionChecker permissionChecker = null;

    if (Validator.isNotNull(principalName)) {
      try {
        User user = UserLocalServiceUtil.fetchUser(PrincipalThreadLocal.getUserId());

        permissionChecker = PermissionCheckerFactoryUtil.create(user);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    if (permissionChecker != null) {
      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    String principalPassword = GetterUtil.getString(context.get("principalPassword"));

    if (Validator.isNotNull(principalPassword)) {
      PrincipalThreadLocal.setPassword(principalPassword);
    }

    Locale siteDefaultLocale = (Locale) context.get("siteDefaultLocale");

    if (siteDefaultLocale != null) {
      LocaleThreadLocal.setSiteDefaultLocale(siteDefaultLocale);
    }

    Locale themeDisplayLocale = (Locale) context.get("themeDisplayLocale");

    if (themeDisplayLocale != null) {
      LocaleThreadLocal.setThemeDisplayLocale(themeDisplayLocale);
    }
  }
  protected void addSearchAnyTags(BooleanQuery contextQuery, SearchContext searchContext)
      throws Exception {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    long[] anyTagIds = _assetEntryQuery.getAnyTagIds();

    if (anyTagIds.length == 0) {
      return;
    }

    long[] filteredAnyTagIds = AssetUtil.filterTagIds(permissionChecker, anyTagIds);

    if (filteredAnyTagIds.length == 0) {
      addImpossibleTerm(contextQuery, Field.ASSET_TAG_IDS);

      return;
    }

    BooleanQuery tagIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (long tagId : anyTagIds) {
      tagIdsQuery.addTerm(Field.ASSET_TAG_IDS, tagId);
    }

    contextQuery.add(tagIdsQuery, BooleanClauseOccur.MUST);
  }
  @Override
  public boolean isDisabled(Object obj) {
    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isRoleProtected(
                permissionChecker,
                user.getUserId(),
                _organization.getOrganizationId(),
                _role.getRoleId())
            || OrganizationMembershipPolicyUtil.isRoleRequired(
                user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

          return true;
        }
      } else {
        if (!OrganizationMembershipPolicyUtil.isRoleAllowed(
            user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

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

    return super.isDisabled(obj);
  }
  public static void updatePermissionFields(String name, String primKey) {
    if (isIndexReadOnly() || !PermissionThreadLocal.isFlushEnabled()) {
      return;
    }

    _searchPermissionChecker.updatePermissionFields(name, primKey);
  }
  private void _checkPermission() throws PrincipalException {
    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if ((permissionChecker == null) || !permissionChecker.isOmniadmin()) {
      throw new PrincipalException();
    }
  }
  public String transform(
      ThemeDisplay themeDisplay, Map<String, Object> contextObjects, String script, String langType)
      throws Exception {

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

    long companyId = 0;
    long companyGroupId = 0;
    long scopeGroupId = 0;
    long siteGroupId = 0;

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

    String templateId = String.valueOf(contextObjects.get("template_id"));

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

    Template template = getTemplate(templateId, script, langType);

    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

    try {
      if (contextObjects != null) {
        for (String key : contextObjects.keySet()) {
          template.put(key, contextObjects.get(key));
        }
      }

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

      String templatesPath = getTemplatesPath(companyId, scopeGroupId);

      template.put("journalTemplatesPath", templatesPath);
      template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      template.put(
          "randomNamespace", PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE);
      template.put("scopeGroupId", scopeGroupId);
      template.put("siteGroupId", siteGroupId);
      template.put("templatesPath", templatesPath);

      // Deprecated variables

      template.put("groupId", scopeGroupId);

      mergeTemplate(template, unsyncStringWriter);
    } catch (Exception e) {
      throw new TransformException("Unhandled exception", e);
    }

    return unsyncStringWriter.toString();
  }
  @Override
  public boolean isDisabled(Object obj) {
    if (!PropsValues.ORGANIZATIONS_ASSIGNMENT_STRICT) {
      return false;
    }

    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isMembershipProtected(
                permissionChecker, user.getUserId(), _organization.getOrganizationId())
            || OrganizationMembershipPolicyUtil.isMembershipRequired(
                user.getUserId(), _organization.getOrganizationId())) {

          return true;
        }
      } else {
        if (!OrganizationMembershipPolicyUtil.isMembershipAllowed(
            user.getUserId(), _organization.getOrganizationId())) {

          return true;
        }
      }

      return !UserPermissionUtil.contains(permissionChecker, user.getUserId(), ActionKeys.UPDATE);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return super.isDisabled(obj);
  }
  protected void copyPreferences(String sourcePortletId, String targetPortletId) {

    Layout layout = getLayout();

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

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

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

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

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePortletPreferences);
    } catch (Exception e) {
    }
  }
  @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);
      }
    }
  }
  protected void testUserPermissions(
      boolean addBaseModelPermission, boolean addParentBaseModelPermission) throws Exception {

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    SearchContext searchContext = SearchContextTestUtil.getSearchContext(group.getGroupId());

    searchContext.setKeywords(getSearchKeywords());

    int initialBaseModelsSearchCount =
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext);

    serviceContext.setAddGroupPermissions(addParentBaseModelPermission);
    serviceContext.setAddGuestPermissions(addParentBaseModelPermission);

    BaseModel<?> parentBaseModel = getParentBaseModel(group, serviceContext);

    serviceContext.setAddGroupPermissions(addBaseModelPermission);
    serviceContext.setAddGuestPermissions(addBaseModelPermission);

    baseModel = addBaseModel(parentBaseModel, true, getSearchKeywords(), serviceContext);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      searchContext.setUserId(user.getUserId());

      int baseModelsCount = initialBaseModelsSearchCount;

      if (addBaseModelPermission && !isCheckBaseModelPermission()) {
        baseModelsCount++;
      }

      Assert.assertEquals(
          baseModelsCount,
          searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext));
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  @Test
  public void testFilterCountByG_N_P() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();
    String[] assetTagProperties = {
      "key" + AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR + "value"
    };

    int initialScopeGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_N_P(
            scopeGroup.getGroupId(), assetTagName, assetTagProperties);
    int initialTagsCountSiteGroup =
        AssetTagFinderUtil.filterCountByG_N_P(
            siteGroup.getGroupId(), assetTagName, assetTagProperties);

    addAssetTag(siteGroup.getGroupId(), assetTagName, assetTagProperties);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      int scopeGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_N_P(
              scopeGroup.getGroupId(), assetTagName, assetTagProperties);

      Assert.assertEquals(initialScopeGroupAssetTagsCount, scopeGroupAssetTagsCount);

      int siteGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_N_P(
              siteGroup.getGroupId(), assetTagName, assetTagProperties);

      Assert.assertEquals(initialTagsCountSiteGroup + 1, siteGroupAssetTagsCount);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  protected void checkWikiPagePermission(long scopeGroupId) throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!permissionChecker.hasPermission(
        scopeGroupId, "com.liferay.portlet.wiki", scopeGroupId, ActionKeys.ADD_NODE)) {

      throw new PrincipalException();
    }
  }
  protected void checkMBMessagePermission(long scopeGroupId) throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!permissionChecker.hasPermission(
        scopeGroupId, "com.liferay.portlet.messageboards", scopeGroupId, ActionKeys.BAN_USER)) {

      throw new PrincipalException();
    }
  }
Example #17
0
  protected void initThreadLocals(User user) throws Exception {
    CompanyThreadLocal.setCompanyId(user.getCompanyId());

    PrincipalThreadLocal.setName(user.getUserId());

    if (!_usePermissionChecker) {
      return;
    }

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (permissionChecker != null) {
      return;
    }

    permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
  }
  @Override
  public void updatePermissionFields(String name, String primKey) {
    if (isIndexReadOnly()) {
      return;
    }

    if (PermissionThreadLocal.isFlushResourcePermissionEnabled(name, primKey)) {

      _searchPermissionChecker.updatePermissionFields(name, primKey);
    }
  }
  @Test
  public void testFilterCountByG_C_N() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    long classNameId = PortalUtil.getClassNameId(BlogsEntry.class);
    String assetTagName = ServiceTestUtil.randomString();

    int initialScopeGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_C_N(scopeGroup.getGroupId(), classNameId, assetTagName);
    int initialSiteGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_C_N(siteGroup.getGroupId(), classNameId, assetTagName);

    addBlogsEntry(scopeGroup.getGroupId(), assetTagName);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      int scopeGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_C_N(scopeGroup.getGroupId(), classNameId, assetTagName);

      Assert.assertEquals(initialScopeGroupAssetTagsCount + 1, scopeGroupAssetTagsCount);

      int siteGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_C_N(siteGroup.getGroupId(), classNameId, assetTagName);

      Assert.assertEquals(initialSiteGroupAssetTagsCount, siteGroupAssetTagsCount);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  protected void addSearchAllCategories(BooleanQuery contextQuery, SearchContext searchContext)
      throws Exception {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    long[] allCategoryIds = _assetEntryQuery.getAllCategoryIds();

    if (allCategoryIds.length == 0) {
      return;
    }

    long[] filteredAllCategoryIds = AssetUtil.filterCategoryIds(permissionChecker, allCategoryIds);

    if (allCategoryIds.length != filteredAllCategoryIds.length) {
      addImpossibleTerm(contextQuery, Field.ASSET_CATEGORY_IDS);

      return;
    }

    BooleanQuery categoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (long allCategoryId : filteredAllCategoryIds) {
      AssetCategory assetCategory = AssetCategoryLocalServiceUtil.fetchAssetCategory(allCategoryId);

      if (assetCategory == null) {
        continue;
      }

      List<Long> categoryIds = new ArrayList<>();

      if (PropsValues.ASSET_CATEGORIES_SEARCH_HIERARCHICAL) {
        categoryIds.addAll(AssetCategoryLocalServiceUtil.getSubcategoryIds(allCategoryId));
      }

      if (categoryIds.isEmpty()) {
        categoryIds.add(allCategoryId);
      }

      BooleanQuery categoryIdQuery = BooleanQueryFactoryUtil.create(searchContext);

      for (long categoryId : categoryIds) {
        categoryIdQuery.addTerm(Field.ASSET_CATEGORY_IDS, categoryId);
      }

      categoryIdsQuery.add(categoryIdQuery, BooleanClauseOccur.MUST);
    }

    contextQuery.add(categoryIdsQuery, BooleanClauseOccur.MUST);
  }
  protected KBArticle getKBArticle(long resourcePrimKey, int status) throws Exception {

    KBArticle kbArticle = KBArticleLocalServiceUtil.fetchLatestKBArticle(resourcePrimKey, status);

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

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!KBArticlePermission.contains(permissionChecker, kbArticle, ActionKeys.VIEW)) {

      return null;
    }

    return kbArticle;
  }
  @Override
  public void initContextUser(long userId) throws AuthException {
    try {
      User user = UserLocalServiceUtil.getUser(userId);

      CompanyThreadLocal.setCompanyId(user.getCompanyId());

      PrincipalThreadLocal.setName(userId);

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      AccessControlThreadLocal.setRemoteAccess(false);
    } catch (Exception e) {
      throw new AuthException(e.getMessage(), e);
    }
  }
Example #23
0
  protected HttpServletRequest setCredentials(
      HttpServletRequest request, HttpSession session, long userId) throws Exception {

    User user = UserLocalServiceUtil.getUser(userId);

    String userIdString = String.valueOf(userId);

    request = new ProtectedServletRequest(request, userIdString);

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(_AUTHENTICATED_USER, userIdString);

    if (_usePermissionChecker) {
      PrincipalThreadLocal.setName(userId);
      PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, false);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    return request;
  }
  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();
    }
  }
  private ActionResult _doProcessAction(
      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());
      }

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

      return ActionResult.EMPTY_ACTION_RESULT;
    }

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

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

    String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);

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

    UploadServletRequest uploadServletRequest = null;

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

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

        if (invokerPortlet.isStrutsPortlet()
            || invokerPortletConfigImpl.isCopyRequestParameters()
            || !invokerPortletConfigImpl.isWARFile()) {

          uploadServletRequest = new UploadServletRequestImpl(request);

          request = uploadServletRequest;
        }
      }

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

        AuthTokenUtil.check(request);
      }

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

      User user = PortalUtil.getUser(request);

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

      actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);

      ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

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

      long scopeGroupId = themeDisplay.getScopeGroupId();

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

      if (access) {
        invokerPortlet.processAction(actionRequestImpl, actionResponseImpl);

        actionResponseImpl.transferHeaders(response);
      }

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

      List<Event> events = actionResponseImpl.getEvents();

      String redirectLocation = actionResponseImpl.getRedirectLocation();

      if (Validator.isNull(redirectLocation) && portlet.isActionURLRedirect()) {

        PortletURL portletURL =
            new PortletURLImpl(
                actionRequestImpl,
                actionRequestImpl.getPortletName(),
                layout.getPlid(),
                PortletRequest.RENDER_PHASE);

        Map<String, String[]> renderParameters = actionResponseImpl.getRenderParameterMap();

        for (Map.Entry<String, String[]> entry : renderParameters.entrySet()) {

          String key = entry.getKey();
          String[] value = entry.getValue();

          portletURL.setParameter(key, value);
        }

        redirectLocation = portletURL.toString();
      }

      return new ActionResult(events, redirectLocation);
    } finally {
      if (uploadServletRequest != null) {
        uploadServletRequest.cleanUp();
      }

      ServiceContextThreadLocal.popServiceContext();
    }
  }
Example #26
0
  public Hits search(
      long companyId,
      long userId,
      String portletId,
      long groupId,
      long[] repositoryIds,
      String keywords,
      int start,
      int end) {

    try {
      SearchContext searchContext = new SearchContext();

      searchContext.setCompanyId(companyId);
      searchContext.setEnd(end);
      searchContext.setEntryClassNames(new String[] {DLFileEntryConstants.getClassName()});
      searchContext.setGroupIds(new long[] {groupId});

      Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

      searchContext.setSearchEngineId(indexer.getSearchEngineId());

      searchContext.setStart(start);
      searchContext.setUserId(userId);

      BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);

      contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);

      if (groupId > 0) {
        Group group = groupLocalService.getGroup(groupId);

        if (group.isLayout()) {
          contextQuery.addRequiredTerm(Field.SCOPE_GROUP_ID, groupId);

          groupId = group.getParentGroupId();
        }

        contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
      }

      if (ArrayUtil.isNotEmpty(repositoryIds)) {
        BooleanQuery repositoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

        for (long repositoryId : repositoryIds) {
          try {
            if (userId > 0) {
              PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

              DLFolderPermission.check(permissionChecker, groupId, repositoryId, ActionKeys.VIEW);
            }

            if (repositoryId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

              repositoryId = groupId;
            }

            TermQuery termQuery =
                TermQueryFactoryUtil.create(searchContext, "repositoryId", repositoryId);

            repositoryIdsQuery.add(termQuery, BooleanClauseOccur.SHOULD);
          } catch (Exception e) {
          }
        }

        contextQuery.add(repositoryIdsQuery, BooleanClauseOccur.MUST);
      }

      BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);

      searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);

      BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

      fullQuery.add(contextQuery, BooleanClauseOccur.MUST);

      List<BooleanClause> clauses = searchQuery.clauses();

      if (!clauses.isEmpty()) {
        fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
      }

      return SearchEngineUtil.search(searchContext, fullQuery);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  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);
    }

    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 = getTypeSettingsProperties().getProperty(columnId);
      }

      columnValue = StringUtil.remove(columnValue, portletId);

      if (hasUserPreferences()) {
        setUserPreference(columnId, columnValue);

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

          ResourceLocalServiceUtil.deleteResource(
              getCompanyId(),
              rootPortletId,
              ResourceConstants.SCOPE_INDIVIDUAL,
              PortletPermissionUtil.getPrimaryKey(getPlid(), portletId));
        } catch (Exception e) {
        }
      } else {
        getTypeSettingsProperties().setProperty(columnId, columnValue);
      }
    }

    if (cleanUp) {
      removeStatesPortletId(portletId);
      removeModesPortletId(portletId);

      try {
        onRemoveFromLayout(portletId);
      } catch (Exception e) {
        _log.error("Unable to fire portlet layout listener event", e);
      }
    }
  }
  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 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;
  }
  @Test
  public void testFilterFindByG_N_P() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();
    String[] assetTagProperties = {
      "key" + AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR + "value"
    };

    List<AssetTag> initialScopeGroupAssetTags =
        AssetTagFinderUtil.filterFindByG_N_P(
            new long[] {scopeGroup.getGroupId()},
            assetTagName,
            assetTagProperties,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            null);
    List<AssetTag> initialSiteGroupAssetTags =
        AssetTagFinderUtil.filterFindByG_N_P(
            new long[] {siteGroup.getGroupId()},
            assetTagName,
            assetTagProperties,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            null);

    addAssetTag(siteGroup.getGroupId(), assetTagName, assetTagProperties);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      List<AssetTag> scopeGroupAssetTags =
          AssetTagFinderUtil.filterFindByG_N_P(
              new long[] {scopeGroup.getGroupId()},
              assetTagName,
              assetTagProperties,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      Assert.assertEquals(initialScopeGroupAssetTags.size(), scopeGroupAssetTags.size());

      List<AssetTag> siteGroupAssetTags =
          AssetTagFinderUtil.filterFindByG_N_P(
              new long[] {siteGroup.getGroupId()},
              assetTagName,
              assetTagProperties,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      Assert.assertEquals(initialSiteGroupAssetTags.size() + 1, siteGroupAssetTags.size());
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }