public static void updatePermissions(Layout layout, boolean addDefaultActionIds)
      throws Exception {

    long companyId = layout.getCompanyId();

    Role role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST);

    String[] actionIds = new String[0];

    String name = Layout.class.getName();
    int scope = ResourceConstants.SCOPE_INDIVIDUAL;
    String primKey = String.valueOf(layout.getPrimaryKey());

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.POWER_USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    if (addDefaultActionIds) {
      actionIds = new String[] {ActionKeys.VIEW};
    }

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);
  }
Exemple #2
0
  protected Map<Long, Set<String>> getActionIds_6(
      long companyId, long[] roleIds, String className, String primKey, List<String> actionIds)
      throws PortalException, SystemException {

    return ResourcePermissionLocalServiceUtil.getAvailableResourcePermissionActionIds(
        companyId, className, ResourceConstants.SCOPE_INDIVIDUAL, primKey, roleIds, actionIds);
  }
  static void ensureUserCustomFieldExists(
      com.liferay.portal.model.User liferayUser, PortletRequest request)
      throws PortalException, SystemException {
    ExpandoBridge exp = liferayUser.getExpandoBridge();
    if (!exp.hasAttribute(CUSTOM_FIELD_PROJECT_GROUP_FILTER)) {
      exp.addAttribute(CUSTOM_FIELD_PROJECT_GROUP_FILTER, ExpandoColumnConstants.STRING, false);
      long companyId = liferayUser.getCompanyId();

      ExpandoColumn column =
          ExpandoColumnLocalServiceUtil.getColumn(
              companyId,
              exp.getClassName(),
              ExpandoTableConstants.DEFAULT_TABLE_NAME,
              CUSTOM_FIELD_PROJECT_GROUP_FILTER);

      String[] roleNames = new String[] {RoleConstants.USER, RoleConstants.POWER_USER};
      for (String roleName : roleNames) {
        Role role = RoleLocalServiceUtil.getRole(companyId, roleName);
        if (role != null && column != null) {
          ResourcePermissionLocalServiceUtil.setResourcePermissions(
              companyId,
              ExpandoColumn.class.getName(),
              ResourceConstants.SCOPE_INDIVIDUAL,
              String.valueOf(column.getColumnId()),
              role.getRoleId(),
              new String[] {ActionKeys.VIEW, ActionKeys.UPDATE});
        }
      }
    }
  }
  @AfterClass
  public static void tearDownClass() throws Exception {
    ResourcePermissionLocalServiceUtil.deleteResourcePermission(_resourcePermission);

    ResourceBlockLocalServiceUtil.deleteResourceBlock(_resourceBlock);

    ResourceBlockPermissionLocalServiceUtil.deleteResourceBlockPermission(_resourceBlockPermission);
  }
  protected void initActionableDynamicQuery(ActionableDynamicQuery actionableDynamicQuery) {
    actionableDynamicQuery.setBaseLocalService(
        com.liferay.portal.service.ResourcePermissionLocalServiceUtil.getService());
    actionableDynamicQuery.setClassLoader(getClassLoader());
    actionableDynamicQuery.setModelClass(ResourcePermission.class);

    actionableDynamicQuery.setPrimaryKeyPropertyName("resourcePermissionId");
  }
  public static ResourcePermission addResourcePermission(
      long actionIds, String name, String primKey, long roleId, int scope) throws Exception {

    long resourcePermissionId =
        CounterLocalServiceUtil.increment(ResourcePermission.class.getName());

    ResourcePermission resourcePermission =
        ResourcePermissionLocalServiceUtil.createResourcePermission(resourcePermissionId);

    resourcePermission.setCompanyId(TestPropsValues.getCompanyId());
    resourcePermission.setName(name);
    resourcePermission.setScope(scope);
    resourcePermission.setPrimKey(primKey);
    resourcePermission.setRoleId(roleId);
    resourcePermission.setActionIds(actionIds);

    return ResourcePermissionLocalServiceUtil.addResourcePermission(resourcePermission);
  }
Exemple #7
0
  protected void convertResourcePermissions(String name, String tableName, String pkColumnName)
      throws Exception {

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      con = DataAccess.getConnection();

      ps = con.prepareStatement("select " + pkColumnName + ", companyId from " + tableName);

      rs = ps.executeQuery();

      while (rs.next()) {
        long primKey = rs.getLong(pkColumnName);
        long companyId = rs.getLong("companyId");

        ResourceBlock resourceBlock = convertResourcePermissions(companyId, name, primKey);

        if (_log.isInfoEnabled() && ((resourceBlock.getResourceBlockId() % 100) == 0)) {

          _log.info("Processed 100 resource blocks for " + name);
        }
      }
    } finally {
      DataAccess.cleanUp(con, ps, rs);
    }

    List<ResourcePermission> resourcePermissions =
        ResourcePermissionLocalServiceUtil.getScopeResourcePermissions(_SCOPES);

    for (ResourcePermission resourcePermission : resourcePermissions) {
      int scope = resourcePermission.getScope();

      if (!name.equals(resourcePermission.getName())) {
        continue;
      }

      if ((scope == ResourceConstants.SCOPE_COMPANY)
          || (scope == ResourceConstants.SCOPE_GROUP_TEMPLATE)) {

        ResourceBlockLocalServiceUtil.setCompanyScopePermissions(
            resourcePermission.getCompanyId(),
            name,
            resourcePermission.getRoleId(),
            resourcePermission.getActionIds());
      } else if (scope == ResourceConstants.SCOPE_GROUP) {
        ResourceBlockLocalServiceUtil.setGroupScopePermissions(
            resourcePermission.getCompanyId(),
            GetterUtil.getLong(resourcePermission.getPrimaryKey()),
            name,
            resourcePermission.getRoleId(),
            resourcePermission.getActionIds());
      }
    }
  }
  protected void deletePermissions_6(long companyId) throws Exception {
    Group group = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

    long plid = LayoutLocalServiceUtil.getDefaultPlid(group.getGroupId(), true);

    Role role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST);

    List<ResourcePermission> resourcePermissions =
        ResourcePermissionLocalServiceUtil.getRoleResourcePermissions(role.getRoleId());

    for (ResourcePermission resourcePermission : resourcePermissions) {
      if (isControlPanelLayout(plid, resourcePermission.getPrimKey())
          || isPrivateLayout(resourcePermission.getName(), resourcePermission.getPrimKey())) {

        ResourcePermissionLocalServiceUtil.deleteResourcePermission(
            resourcePermission.getResourcePermissionId());
      }
    }
  }
  protected void deleteRolePermissions(PortletDataContext portletDataContext, Role importedRole)
      throws SystemException {

    List<ResourcePermission> resourcePermissions =
        ResourcePermissionLocalServiceUtil.getRoleResourcePermissions(
            importedRole.getRoleId(),
            new int[] {ResourceConstants.SCOPE_COMPANY, ResourceConstants.SCOPE_GROUP_TEMPLATE},
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS);

    for (ResourcePermission resourcePermission : resourcePermissions) {
      ResourcePermissionLocalServiceUtil.deleteResourcePermission(resourcePermission);
    }

    List<ResourcePermission> groupResourcePermissions =
        ResourcePermissionLocalServiceUtil.getRoleResourcePermissions(
            importedRole.getRoleId(),
            new int[] {ResourceConstants.SCOPE_GROUP},
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS);

    for (ResourcePermission groupResourcePermission : groupResourcePermissions) {

      long groupId = GetterUtil.getLong(groupResourcePermission.getPrimKey());

      if ((groupId == portletDataContext.getCompanyGroupId())
          || (groupId == portletDataContext.getUserPersonalSiteGroupId())) {

        ResourcePermissionLocalServiceUtil.deleteResourcePermission(groupResourcePermission);
      }
    }

    List<ResourceTypePermission> resourceTypePermissions =
        getResourceTypePermissions(portletDataContext, importedRole);

    for (ResourceTypePermission resourceTypePermission : resourceTypePermissions) {

      ResourceTypePermissionLocalServiceUtil.deleteResourceTypePermission(resourceTypePermission);
    }
  }
  @Override
  public ActionableDynamicQuery getActionableDynamicQuery() {
    ActionableDynamicQuery actionableDynamicQuery = new DefaultActionableDynamicQuery();

    actionableDynamicQuery.setBaseLocalService(
        com.liferay.portal.service.ResourcePermissionLocalServiceUtil.getService());
    actionableDynamicQuery.setClassLoader(getClassLoader());
    actionableDynamicQuery.setModelClass(ResourcePermission.class);

    actionableDynamicQuery.setPrimaryKeyPropertyName("resourcePermissionId");

    return actionableDynamicQuery;
  }
  protected Map<Long, Set<String>> getActionIds(
      long companyId, long[] roleIds, String className, long primKey, List<String> actionIds)
      throws PortalException, SystemException {

    if (ResourceBlockLocalServiceUtil.isSupported(className)) {
      return ResourceBlockPermissionLocalServiceUtil.getAvailableResourceBlockPermissionActionIds(
          roleIds, className, primKey, actionIds);
    } else {
      return ResourcePermissionLocalServiceUtil.getAvailableResourcePermissionActionIds(
          companyId,
          className,
          ResourceConstants.SCOPE_INDIVIDUAL,
          String.valueOf(primKey),
          roleIds,
          actionIds);
    }
  }
Exemple #12
0
  protected ResourceBlockPermissionsContainer getResourceBlockPermissionsContainer(
      long companyId, long groupId, String name, long primKey) throws SystemException {

    ResourceBlockPermissionsContainer resourceBlockPermissionContainer =
        new ResourceBlockPermissionsContainer();

    List<ResourcePermission> resourcePermissions =
        ResourcePermissionLocalServiceUtil.getResourceResourcePermissions(
            companyId, groupId, name, String.valueOf(primKey));

    for (ResourcePermission resourcePermission : resourcePermissions) {
      resourceBlockPermissionContainer.addPermission(
          resourcePermission.getRoleId(), resourcePermission.getActionIds());
    }

    return resourceBlockPermissionContainer;
  }
  protected void addPortletModelViewPermission() throws Exception {
    RoleTestUtil.addResourcePermission(
        getRoleName(),
        getResourceName(),
        ResourceConstants.SCOPE_GROUP,
        getPrimKey(),
        ActionKeys.VIEW);

    Role role = RoleLocalServiceUtil.getRole(TestPropsValues.getCompanyId(), getRoleName());

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        group.getCompanyId(),
        getResourceName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        getPrimKey(),
        role.getRoleId(),
        new String[] {ActionKeys.VIEW});
  }
Exemple #14
0
  public static void propagatePermissions(
      long companyId, long groupId, long parentMessageId, ServiceContext serviceContext)
      throws PortalException {

    MBMessage parentMessage = MBMessageLocalServiceUtil.getMBMessage(parentMessageId);

    Role defaultGroupRole = RoleLocalServiceUtil.getDefaultGroupRole(groupId);
    Role guestRole = RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST);

    long[] roleIds = {defaultGroupRole.getRoleId(), guestRole.getRoleId()};

    List<String> actionIds = ResourceActionsUtil.getModelResourceActions(MBMessage.class.getName());

    Map<Long, Set<String>> roleIdsToActionIds =
        ResourcePermissionLocalServiceUtil.getAvailableResourcePermissionActionIds(
            companyId,
            MBMessage.class.getName(),
            ResourceConstants.SCOPE_INDIVIDUAL,
            String.valueOf(parentMessage.getMessageId()),
            roleIds,
            actionIds);

    Set<String> defaultGroupActionIds = roleIdsToActionIds.get(defaultGroupRole.getRoleId());

    if (defaultGroupActionIds == null) {
      serviceContext.setGroupPermissions(new String[] {});
    } else {
      serviceContext.setGroupPermissions(
          defaultGroupActionIds.toArray(new String[defaultGroupActionIds.size()]));
    }

    Set<String> guestActionIds = roleIdsToActionIds.get(guestRole.getRoleId());

    if (guestActionIds == null) {
      serviceContext.setGuestPermissions(new String[] {});
    } else {
      serviceContext.setGuestPermissions(guestActionIds.toArray(new String[guestActionIds.size()]));
    }
  }
  public void importPermissions(String resourceName, long resourcePK, long newResourcePK)
      throws PortalException, SystemException {

    if (!MapUtil.getBoolean(_parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {

      return;
    }

    List<KeyValuePair> permissions =
        _permissionsMap.get(getPrimaryKeyString(resourceName, resourcePK));

    if (permissions == null) {
      return;
    }

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

    for (KeyValuePair permission : permissions) {
      String roleName = permission.getKey();

      Role role = null;

      Team team = null;

      if (roleName.startsWith(PermissionExporter.ROLE_TEAM_PREFIX)) {
        roleName = roleName.substring(PermissionExporter.ROLE_TEAM_PREFIX.length());

        try {
          team = TeamLocalServiceUtil.getTeam(_groupId, roleName);
        } catch (NoSuchTeamException nste) {
          if (_log.isWarnEnabled()) {
            _log.warn("Team " + roleName + " does not exist");
          }

          continue;
        }
      }

      try {
        if (team != null) {
          role = RoleLocalServiceUtil.getTeamRole(_companyId, team.getTeamId());
        } else {
          role = RoleLocalServiceUtil.getRole(_companyId, roleName);
        }
      } catch (NoSuchRoleException nsre) {
        if (_log.isWarnEnabled()) {
          _log.warn("Role " + roleName + " does not exist");
        }

        continue;
      }

      String[] actionIds = StringUtil.split(permission.getValue());

      roleIdsToActionIds.put(role.getRoleId(), actionIds);
    }

    if (roleIdsToActionIds.isEmpty()) {
      return;
    }

    if (ResourceBlockLocalServiceUtil.isSupported(resourceName)) {
      ResourceBlockLocalServiceUtil.setIndividualScopePermissions(
          _companyId, _groupId, resourceName, newResourcePK, roleIdsToActionIds);
    } else {
      ResourcePermissionLocalServiceUtil.setResourcePermissions(
          _companyId,
          resourceName,
          ResourceConstants.SCOPE_INDIVIDUAL,
          String.valueOf(newResourcePK),
          roleIdsToActionIds);
    }
  }
  protected void importLayout(
      PortletDataContext portletDataContext,
      User user,
      LayoutCache layoutCache,
      List<Layout> previousLayouts,
      List<Layout> newLayouts,
      Map<Long, Layout> newLayoutsMap,
      Set<Long> newLayoutIds,
      String portletsMergeMode,
      String themeId,
      String colorSchemeId,
      String layoutsImportMode,
      boolean privateLayout,
      boolean importPermissions,
      boolean importPublicLayoutPermissions,
      boolean importUserPermissions,
      boolean importThemeSettings,
      Element rootElement,
      Element layoutElement)
      throws Exception {

    long groupId = portletDataContext.getGroupId();

    String layoutUuid = GetterUtil.getString(layoutElement.attributeValue("layout-uuid"));

    long layoutId = GetterUtil.getInteger(layoutElement.attributeValue("layout-id"));

    long oldLayoutId = layoutId;

    boolean deleteLayout = GetterUtil.getBoolean(layoutElement.attributeValue("delete"));

    if (deleteLayout) {
      Layout layout = LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId(layoutUuid, groupId);

      if (layout != null) {
        newLayoutsMap.put(oldLayoutId, layout);

        ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

        LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext);
      }

      return;
    }

    String path = layoutElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
      return;
    }

    Layout layout = (Layout) portletDataContext.getZipEntryAsObject(path);

    Layout existingLayout = null;
    Layout importedLayout = null;

    String friendlyURL = layout.getFriendlyURL();

    if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_ADD_AS_NEW)) {

      layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      friendlyURL = StringPool.SLASH + layoutId;
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME)) {

      Locale locale = LocaleUtil.getDefault();

      String localizedName = layout.getName(locale);

      for (Layout curLayout : previousLayouts) {
        if (localizedName.equals(curLayout.getName(locale))
            || friendlyURL.equals(curLayout.getFriendlyURL())) {

          existingLayout = curLayout;

          break;
        }
      }

      if (existingLayout == null) {
        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      }
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

      existingLayout = LayoutUtil.fetchByG_P_SPLU(groupId, privateLayout, layout.getUuid());

      if (SitesUtil.isLayoutModifiedSinceLastMerge(existingLayout)) {
        newLayoutsMap.put(oldLayoutId, existingLayout);

        return;
      }
    } else {

      // The default behaviour of import mode is
      // PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID

      existingLayout = LayoutUtil.fetchByUUID_G(layout.getUuid(), groupId);

      if (existingLayout == null) {
        existingLayout = LayoutUtil.fetchByG_P_F(groupId, privateLayout, friendlyURL);
      }

      if (existingLayout == null) {
        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      }
    }

    if (_log.isDebugEnabled()) {
      if (existingLayout == null) {
        _log.debug(
            "Layout with {groupId="
                + groupId
                + ",privateLayout="
                + privateLayout
                + ",layoutId="
                + layoutId
                + "} does not exist");
      } else {
        _log.debug(
            "Layout with {groupId="
                + groupId
                + ",privateLayout="
                + privateLayout
                + ",layoutId="
                + layoutId
                + "} exists");
      }
    }

    if (existingLayout == null) {
      long plid = CounterLocalServiceUtil.increment();

      importedLayout = LayoutUtil.create(plid);

      if (layoutsImportMode.equals(
          PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        importedLayout.setSourcePrototypeLayoutUuid(layout.getUuid());

        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      } else {
        importedLayout.setUuid(layout.getUuid());
        importedLayout.setCreateDate(layout.getCreateDate());
        importedLayout.setModifiedDate(layout.getModifiedDate());
        importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
        importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());
        importedLayout.setSourcePrototypeLayoutUuid(layout.getSourcePrototypeLayoutUuid());
      }

      importedLayout.setGroupId(groupId);
      importedLayout.setPrivateLayout(privateLayout);
      importedLayout.setLayoutId(layoutId);

      // Resources

      boolean addGroupPermissions = true;

      Group group = importedLayout.getGroup();

      if (privateLayout && group.isUser()) {
        addGroupPermissions = false;
      }

      boolean addGuestPermissions = false;

      if (!privateLayout || layout.isTypeControlPanel()) {
        addGuestPermissions = true;
      }

      ResourceLocalServiceUtil.addResources(
          user.getCompanyId(),
          groupId,
          user.getUserId(),
          Layout.class.getName(),
          importedLayout.getPlid(),
          false,
          addGroupPermissions,
          addGuestPermissions);

      LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

      importedLayout.setLayoutSet(layoutSet);
    } else {
      importedLayout = existingLayout;
    }

    newLayoutsMap.put(oldLayoutId, importedLayout);

    long parentLayoutId = layout.getParentLayoutId();

    Node parentLayoutNode =
        rootElement.selectSingleNode("./layouts/layout[@layout-id='" + parentLayoutId + "']");

    String parentLayoutUuid =
        GetterUtil.getString(layoutElement.attributeValue("parent-layout-uuid"));

    if ((parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID)
        && (parentLayoutNode != null)) {

      importLayout(
          portletDataContext,
          user,
          layoutCache,
          previousLayouts,
          newLayouts,
          newLayoutsMap,
          newLayoutIds,
          portletsMergeMode,
          themeId,
          colorSchemeId,
          layoutsImportMode,
          privateLayout,
          importPermissions,
          importPublicLayoutPermissions,
          importUserPermissions,
          importThemeSettings,
          rootElement,
          (Element) parentLayoutNode);

      Layout parentLayout = newLayoutsMap.get(parentLayoutId);

      parentLayoutId = parentLayout.getLayoutId();
    } else if (Validator.isNotNull(parentLayoutUuid)) {
      Layout parentLayout =
          LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(parentLayoutUuid, groupId);

      parentLayoutId = parentLayout.getLayoutId();
    }

    if (_log.isDebugEnabled()) {
      _log.debug(
          "Importing layout with layout id "
              + layoutId
              + " and parent layout id "
              + parentLayoutId);
    }

    importedLayout.setCompanyId(user.getCompanyId());
    importedLayout.setParentLayoutId(parentLayoutId);
    importedLayout.setName(layout.getName());
    importedLayout.setTitle(layout.getTitle());
    importedLayout.setDescription(layout.getDescription());
    importedLayout.setKeywords(layout.getKeywords());
    importedLayout.setRobots(layout.getRobots());
    importedLayout.setType(layout.getType());

    if (layout.isTypeArticle()) {
      importJournalArticle(portletDataContext, layout, layoutElement);

      importedLayout.setTypeSettings(layout.getTypeSettings());
    } else if (layout.isTypePortlet()
        && Validator.isNotNull(layout.getTypeSettings())
        && !portletsMergeMode.equals(PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE)) {

      mergePortlets(importedLayout, layout.getTypeSettings(), portletsMergeMode);
    } else if (layout.isTypeLinkToLayout()) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

      long linkToLayoutId =
          GetterUtil.getLong(
              typeSettingsProperties.getProperty("linkToLayoutId", StringPool.BLANK));

      if (linkToLayoutId > 0) {
        Node linkedLayoutNode =
            rootElement.selectSingleNode("./layouts/layout[@layout-id='" + linkToLayoutId + "']");

        if (linkedLayoutNode != null) {
          importLayout(
              portletDataContext,
              user,
              layoutCache,
              previousLayouts,
              newLayouts,
              newLayoutsMap,
              newLayoutIds,
              portletsMergeMode,
              themeId,
              colorSchemeId,
              layoutsImportMode,
              privateLayout,
              importPermissions,
              importPublicLayoutPermissions,
              importUserPermissions,
              importThemeSettings,
              rootElement,
              (Element) linkedLayoutNode);

          Layout linkedLayout = newLayoutsMap.get(linkToLayoutId);

          typeSettingsProperties.setProperty(
              "privateLayout", String.valueOf(linkedLayout.getPrivateLayout()));
          typeSettingsProperties.setProperty(
              "linkToLayoutId", String.valueOf(linkedLayout.getLayoutId()));
        } else {
          if (_log.isWarnEnabled()) {
            StringBundler sb = new StringBundler();

            sb.append("Unable to link layout with friendly URL ");
            sb.append(layout.getFriendlyURL());
            sb.append(" and layout id ");
            sb.append(layout.getLayoutId());
            sb.append(" to layout with layout id ");
            sb.append(linkToLayoutId);

            _log.warn(sb.toString());
          }
        }
      }

      importedLayout.setTypeSettings(layout.getTypeSettings());
    } else {
      importedLayout.setTypeSettings(layout.getTypeSettings());
    }

    importedLayout.setHidden(layout.isHidden());
    importedLayout.setFriendlyURL(friendlyURL);

    if (importThemeSettings) {
      importedLayout.setThemeId(layout.getThemeId());
      importedLayout.setColorSchemeId(layout.getColorSchemeId());
    } else {
      importedLayout.setThemeId(StringPool.BLANK);
      importedLayout.setColorSchemeId(StringPool.BLANK);
    }

    importedLayout.setWapThemeId(layout.getWapThemeId());
    importedLayout.setWapColorSchemeId(layout.getWapColorSchemeId());
    importedLayout.setCss(layout.getCss());
    importedLayout.setPriority(layout.getPriority());
    importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
    importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());

    StagingUtil.updateLastImportSettings(layoutElement, importedLayout, portletDataContext);

    fixTypeSettings(importedLayout);

    importedLayout.setIconImage(false);

    if (layout.isIconImage()) {
      String iconImagePath = layoutElement.elementText("icon-image-path");

      byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(iconImagePath);

      if ((iconBytes != null) && (iconBytes.length > 0)) {
        importedLayout.setIconImage(true);

        if (importedLayout.getIconImageId() == 0) {
          long iconImageId = CounterLocalServiceUtil.increment();

          importedLayout.setIconImageId(iconImageId);
        }

        ImageLocalServiceUtil.updateImage(importedLayout.getIconImageId(), iconBytes);
      }
    } else {
      ImageLocalServiceUtil.deleteImage(importedLayout.getIconImageId());
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(layoutElement, importedLayout, null);

    importedLayout.setExpandoBridgeAttributes(serviceContext);

    LayoutUtil.update(importedLayout, false);

    portletDataContext.setPlid(importedLayout.getPlid());
    portletDataContext.setOldPlid(layout.getPlid());

    newLayoutIds.add(importedLayout.getLayoutId());

    newLayouts.add(importedLayout);

    // Layout permissions

    if (importPermissions) {
      _permissionImporter.importLayoutPermissions(
          layoutCache,
          portletDataContext.getCompanyId(),
          groupId,
          user.getUserId(),
          importedLayout,
          layoutElement,
          rootElement,
          importUserPermissions);
    }

    if (importPublicLayoutPermissions) {
      String resourceName = Layout.class.getName();
      String resourcePrimKey = String.valueOf(importedLayout.getPlid());

      Role guestRole =
          RoleLocalServiceUtil.getRole(importedLayout.getCompanyId(), RoleConstants.GUEST);

      if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) {
        Resource resource =
            layoutCache.getResource(
                importedLayout.getCompanyId(),
                groupId,
                resourceName,
                ResourceConstants.SCOPE_INDIVIDUAL,
                resourcePrimKey,
                false);

        PermissionLocalServiceUtil.setRolePermissions(
            guestRole.getRoleId(), new String[] {ActionKeys.VIEW}, resource.getResourceId());
      } else if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
        ResourcePermissionLocalServiceUtil.setResourcePermissions(
            importedLayout.getCompanyId(),
            resourceName,
            ResourceConstants.SCOPE_INDIVIDUAL,
            resourcePrimKey,
            guestRole.getRoleId(),
            new String[] {ActionKeys.VIEW});
      } else {
        Resource resource =
            layoutCache.getResource(
                importedLayout.getCompanyId(),
                groupId,
                resourceName,
                ResourceConstants.SCOPE_INDIVIDUAL,
                resourcePrimKey,
                false);

        PermissionLocalServiceUtil.setGroupPermissions(
            groupId, new String[] {ActionKeys.VIEW}, resource.getResourceId());
      }
    }

    _portletImporter.importPortletData(
        portletDataContext, PortletKeys.LAYOUT_CONFIGURATION, null, layoutElement);
  }
  protected Query doGetPermissionQuery_6(
      long companyId,
      long[] groupIds,
      long userId,
      String className,
      Query query,
      SearchContext searchContext,
      AdvancedPermissionChecker advancedPermissionChecker,
      List<Group> groups,
      List<Role> roles,
      List<UserGroupRole> userGroupRoles,
      Map<Long, List<Role>> groupIdsToRoles)
      throws Exception {

    BooleanQuery permissionQuery = BooleanQueryFactoryUtil.create(searchContext);

    if (userId > 0) {
      permissionQuery.addTerm(Field.USER_ID, userId);
    }

    BooleanQuery groupsQuery = BooleanQueryFactoryUtil.create(searchContext);
    BooleanQuery rolesQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (Role role : roles) {
      String roleName = role.getName();

      if (roleName.equals(RoleConstants.ADMINISTRATOR)) {
        return query;
      }

      if (ResourcePermissionLocalServiceUtil.hasResourcePermission(
          companyId,
          className,
          ResourceConstants.SCOPE_COMPANY,
          String.valueOf(companyId),
          role.getRoleId(),
          ActionKeys.VIEW)) {

        return query;
      }

      if ((role.getType() == RoleConstants.TYPE_REGULAR)
          && ResourcePermissionLocalServiceUtil.hasResourcePermission(
              companyId,
              className,
              ResourceConstants.SCOPE_GROUP_TEMPLATE,
              String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
              role.getRoleId(),
              ActionKeys.VIEW)) {

        return query;
      }

      for (Group group : groups) {
        if (ResourcePermissionLocalServiceUtil.hasResourcePermission(
            companyId,
            className,
            ResourceConstants.SCOPE_GROUP,
            String.valueOf(group.getGroupId()),
            role.getRoleId(),
            ActionKeys.VIEW)) {

          groupsQuery.addTerm(Field.GROUP_ID, group.getGroupId());
        }

        if ((role.getType() != RoleConstants.TYPE_REGULAR)
            && ResourcePermissionLocalServiceUtil.hasResourcePermission(
                companyId,
                className,
                ResourceConstants.SCOPE_GROUP_TEMPLATE,
                String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
                role.getRoleId(),
                ActionKeys.VIEW)) {

          List<Role> groupRoles = groupIdsToRoles.get(group.getGroupId());

          if (groupRoles.contains(role)) {
            groupsQuery.addTerm(Field.GROUP_ID, group.getGroupId());
          }
        }

        if (group.isSite()
            && !roleName.equals(RoleConstants.SITE_MEMBER)
            && (role.getType() == RoleConstants.TYPE_SITE)) {

          rolesQuery.addTerm(
              Field.GROUP_ROLE_ID, group.getGroupId() + StringPool.DASH + role.getRoleId());
        }
      }

      rolesQuery.addTerm(Field.ROLE_ID, role.getRoleId());
    }

    for (Group group : groups) {
      addRequiredMemberRole(group, rolesQuery);
    }

    for (UserGroupRole userGroupRole : userGroupRoles) {
      rolesQuery.addTerm(
          Field.GROUP_ROLE_ID,
          userGroupRole.getGroupId() + StringPool.DASH + userGroupRole.getRoleId());
    }

    if (groupsQuery.hasClauses()) {
      permissionQuery.add(groupsQuery, BooleanClauseOccur.SHOULD);
    }

    if (rolesQuery.hasClauses()) {
      permissionQuery.add(rolesQuery, BooleanClauseOccur.SHOULD);
    }

    BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

    fullQuery.add(query, BooleanClauseOccur.MUST);
    fullQuery.add(permissionQuery, BooleanClauseOccur.MUST);

    return fullQuery;
  }
  protected void fixOrganizationRolePermissions() throws Exception {
    DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(ResourcePermission.class);

    dynamicQuery.add(RestrictionsFactoryUtil.eq("name", Organization.class.getName()));

    List<ResourcePermission> resourcePermissions =
        ResourcePermissionLocalServiceUtil.dynamicQuery(dynamicQuery);

    for (ResourcePermission resourcePermission : resourcePermissions) {
      ResourcePermission groupResourcePermission = null;

      try {
        groupResourcePermission =
            ResourcePermissionLocalServiceUtil.getResourcePermission(
                resourcePermission.getCompanyId(),
                Group.class.getName(),
                resourcePermission.getScope(),
                resourcePermission.getPrimKey(),
                resourcePermission.getRoleId());
      } catch (Exception e) {
        ResourcePermissionLocalServiceUtil.setResourcePermissions(
            resourcePermission.getCompanyId(),
            Group.class.getName(),
            resourcePermission.getScope(),
            resourcePermission.getPrimKey(),
            resourcePermission.getRoleId(),
            ResourcePermissionLocalServiceImpl.EMPTY_ACTION_IDS);

        groupResourcePermission =
            ResourcePermissionLocalServiceUtil.getResourcePermission(
                resourcePermission.getCompanyId(),
                Group.class.getName(),
                resourcePermission.getScope(),
                resourcePermission.getPrimKey(),
                resourcePermission.getRoleId());
      }

      long organizationActions = resourcePermission.getActionIds();
      long groupActions = groupResourcePermission.getActionIds();

      for (Object[] actionIdToMask : _ORGANIZATION_ACTION_IDS_TO_MASKS) {
        long organizationActionMask = (Long) actionIdToMask[1];
        long groupActionMask = (Long) actionIdToMask[2];

        if ((organizationActions & organizationActionMask) == organizationActionMask) {

          organizationActions = organizationActions & (~organizationActionMask);
          groupActions = groupActions | groupActionMask;
        }
      }

      try {
        resourcePermission.resetOriginalValues();

        resourcePermission.setActionIds(organizationActions);

        ResourcePermissionLocalServiceUtil.updateResourcePermission(resourcePermission);

        groupResourcePermission.resetOriginalValues();
        groupResourcePermission.setActionIds(groupActions);

        ResourcePermissionLocalServiceUtil.updateResourcePermission(groupResourcePermission);
      } catch (Exception e) {
        _log.error(e, e);
      }
    }

    PermissionCacheUtil.clearCache();
  }
  public boolean containsWithoutViewableGroup(
      PermissionChecker permissionChecker,
      Layout layout,
      String controlPanelCategory,
      boolean checkLayoutUpdateable,
      String actionId)
      throws PortalException, SystemException {

    if (checkLayoutUpdateable
        && !actionId.equals(ActionKeys.CUSTOMIZE)
        && !actionId.equals(ActionKeys.VIEW)
        && (layout instanceof VirtualLayout)) {

      return false;
    }

    if (actionId.equals(ActionKeys.CUSTOMIZE) && (layout instanceof VirtualLayout)) {

      VirtualLayout virtualLayout = (VirtualLayout) layout;

      layout = virtualLayout.getWrappedModel();
    }

    if (actionId.equals(ActionKeys.DELETE) && !SitesUtil.isLayoutDeleteable(layout)) {

      return false;
    }

    Group group = layout.getGroup();

    if (checkLayoutUpdateable
        && !group.isLayoutSetPrototype()
        && isAttemptToModifyLockedLayout(layout, actionId)) {

      return false;
    }

    User user = UserLocalServiceUtil.getUserById(permissionChecker.getUserId());

    if ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6)
        && !user.isDefaultUser()
        && !group.isUser()) {

      // This is new way of doing an ownership check without having to
      // have a userId field on the model. When the instance model was
      // first created, we set the user's userId as the ownerId of the
      // individual scope ResourcePermission of the Owner Role.
      // Therefore, ownership can be determined by obtaining the Owner
      // role ResourcePermission for the current instance model and
      // testing it with the hasOwnerPermission call.

      ResourcePermission resourcePermission =
          ResourcePermissionLocalServiceUtil.getResourcePermission(
              layout.getCompanyId(),
              Layout.class.getName(),
              ResourceConstants.SCOPE_INDIVIDUAL,
              String.valueOf(layout.getPlid()),
              permissionChecker.getOwnerRoleId());

      if (permissionChecker.hasOwnerPermission(
          layout.getCompanyId(),
          Layout.class.getName(),
          String.valueOf(layout.getPlid()),
          resourcePermission.getOwnerId(),
          actionId)) {

        return true;
      }
    }

    if (GroupPermissionUtil.contains(
        permissionChecker, layout.getGroupId(), ActionKeys.MANAGE_LAYOUTS)) {

      return true;
    } else if (actionId.equals(ActionKeys.ADD_LAYOUT)
        && GroupPermissionUtil.contains(
            permissionChecker, layout.getGroupId(), ActionKeys.ADD_LAYOUT)) {

      return true;
    }

    if (PropsValues.PERMISSIONS_VIEW_DYNAMIC_INHERITANCE && !actionId.equals(ActionKeys.VIEW)) {

      // Check upward recursively to see if any pages above grant the
      // action

      long parentLayoutId = layout.getParentLayoutId();

      while (parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID) {
        Layout parentLayout =
            LayoutLocalServiceUtil.getLayout(
                layout.getGroupId(), layout.isPrivateLayout(), parentLayoutId);

        if (contains(permissionChecker, parentLayout, controlPanelCategory, actionId)) {

          return true;
        }

        parentLayoutId = parentLayout.getParentLayoutId();
      }
    }

    try {
      if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
        if (ResourcePermissionLocalServiceUtil.getResourcePermissionsCount(
                layout.getCompanyId(),
                Layout.class.getName(),
                ResourceConstants.SCOPE_INDIVIDUAL,
                String.valueOf(layout.getPlid()))
            == 0) {

          throw new NoSuchResourceException();
        }
      } else {
        ResourceLocalServiceUtil.getResource(
            layout.getCompanyId(),
            Layout.class.getName(),
            ResourceConstants.SCOPE_INDIVIDUAL,
            String.valueOf(layout.getPlid()));
      }
    } catch (NoSuchResourceException nsre) {
      boolean addGroupPermission = true;
      boolean addGuestPermission = true;

      if (layout.isPrivateLayout()) {
        addGuestPermission = false;
      }

      ResourceLocalServiceUtil.addResources(
          layout.getCompanyId(),
          layout.getGroupId(),
          0,
          Layout.class.getName(),
          layout.getPlid(),
          false,
          addGroupPermission,
          addGuestPermission);
    }

    return permissionChecker.hasPermission(
        layout.getGroupId(), Layout.class.getName(), layout.getPlid(), actionId);
  }
  protected void doAddPermissionFields_6(
      long companyId, long groupId, String className, String classPK, Document doc)
      throws Exception {

    Group group = null;

    if (groupId > 0) {
      group = GroupLocalServiceUtil.getGroup(groupId);
    }

    List<Role> roles =
        ListUtil.copy(ResourceActionsUtil.getRoles(companyId, group, className, null));

    if (groupId > 0) {
      List<Role> teamRoles = RoleLocalServiceUtil.getTeamRoles(groupId);

      roles.addAll(teamRoles);
    }

    long[] roleIdsArray = new long[roles.size()];

    for (int i = 0; i < roleIdsArray.length; i++) {
      Role role = roles.get(i);

      roleIdsArray[i] = role.getRoleId();
    }

    boolean[] hasResourcePermissions = null;

    if (ResourceBlockLocalServiceUtil.isSupported(className)) {
      ResourceBlockIdsBag resourceBlockIdsBag =
          ResourceBlockLocalServiceUtil.getResourceBlockIdsBag(
              companyId, groupId, className, roleIdsArray);

      long actionId = ResourceBlockLocalServiceUtil.getActionId(className, ActionKeys.VIEW);

      List<Long> resourceBlockIds = resourceBlockIdsBag.getResourceBlockIds(actionId);

      hasResourcePermissions = new boolean[roleIdsArray.length];

      for (long resourceBlockId : resourceBlockIds) {
        for (int i = 0; i < roleIdsArray.length; i++) {
          int count =
              ResourceBlockPermissionLocalServiceUtil.getResourceBlockPermissionsCount(
                  resourceBlockId, roleIdsArray[i]);

          hasResourcePermissions[i] = (count > 0);
        }
      }
    } else {
      hasResourcePermissions =
          ResourcePermissionLocalServiceUtil.hasResourcePermissions(
              companyId,
              className,
              ResourceConstants.SCOPE_INDIVIDUAL,
              classPK,
              roleIdsArray,
              ActionKeys.VIEW);
    }

    List<Long> roleIds = new ArrayList<Long>();
    List<String> groupRoleIds = new ArrayList<String>();

    for (int i = 0; i < hasResourcePermissions.length; i++) {
      if (!hasResourcePermissions[i]) {
        continue;
      }

      Role role = roles.get(i);

      if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
          || (role.getType() == RoleConstants.TYPE_SITE)) {

        groupRoleIds.add(groupId + StringPool.DASH + role.getRoleId());
      } else {
        roleIds.add(role.getRoleId());
      }
    }

    doc.addKeyword(Field.ROLE_ID, roleIds.toArray(new Long[roleIds.size()]));
    doc.addKeyword(Field.GROUP_ROLE_ID, groupRoleIds.toArray(new String[groupRoleIds.size()]));
  }
 /*
  * NOTE FOR DEVELOPERS:
  *
  * Never modify or reference this class directly. All methods that expect a resource permission model instance should use the {@link ResourcePermission} interface instead.
  */
 public void save() throws SystemException {
   ResourcePermissionLocalServiceUtil.updateResourcePermission(this);
 }