@Test
  public void testOrganizationMemberRule() throws Exception {
    ServiceContext serviceContext = ServiceTestUtil.getServiceContext();

    AnonymousUser anonymousUser =
        _anonymousUserLocalService.addAnonymousUser(
            TestPropsValues.getUserId(), "127.0.0.1", StringPool.BLANK, serviceContext);

    Rule rule = _rulesRegistry.getRule("OrganizationMemberRule");

    Organization organization =
        OrganizationLocalServiceUtil.addOrganization(
            TestPropsValues.getUserId(),
            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID,
            StringUtil.randomString(),
            false);

    OrganizationLocalServiceUtil.addUserOrganization(
        TestPropsValues.getUserId(), organization.getOrganizationId());

    RuleInstance ruleInstance =
        _ruleInstanceLocalService.addRuleInstance(
            TestPropsValues.getUserId(),
            rule.getRuleKey(),
            0,
            String.valueOf(organization.getOrganizationId()),
            serviceContext);

    Assert.assertTrue(rule.evaluate(null, ruleInstance, anonymousUser));
  }
  @Override
  protected Long getImportPortletPreferencesNewPrimaryKey(
      PortletDataContext portletDataContext,
      Class<?> clazz,
      long companyGroupId,
      Map<Long, Long> primaryKeys,
      String uuid)
      throws Exception {

    if (Validator.isNumber(uuid)) {
      long oldPrimaryKey = GetterUtil.getLong(uuid);

      return MapUtil.getLong(primaryKeys, oldPrimaryKey, oldPrimaryKey);
    }

    String className = clazz.getName();

    if (className.equals(Organization.class.getName())) {
      Organization organization =
          OrganizationUtil.fetchByUuid_C_First(uuid, portletDataContext.getCompanyId(), null);

      if (organization != null) {
        return organization.getOrganizationId();
      }
    }

    return null;
  }
  public void joinOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

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

    Organization organization = _organizationLocalService.getOrganization(group.getClassPK());

    Role role =
        _roleLocalService.getRole(themeDisplay.getCompanyId(), "Organization Administrator");

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

    userParams.put("userGroupRole", new Long[] {group.getGroupId(), role.getRoleId()});

    List<User> users =
        _userLocalService.search(
            themeDisplay.getCompanyId(),
            null,
            WorkflowConstants.STATUS_APPROVED,
            userParams,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            (OrderByComparator<User>) null);

    if (users.isEmpty()) {
      Role adminRole =
          _roleLocalService.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR);

      userParams.clear();

      userParams.put("usersRoles", adminRole.getRoleId());

      users =
          _userLocalService.search(
              themeDisplay.getCompanyId(),
              null,
              WorkflowConstants.STATUS_APPROVED,
              userParams,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              (OrderByComparator<User>) null);
    }

    JSONObject extraDataJSONObject = getExtraDataJSONObject(actionRequest);

    for (User user : users) {
      _socialRequestLocalService.addRequest(
          themeDisplay.getUserId(),
          0,
          Organization.class.getName(),
          organization.getOrganizationId(),
          MembersRequestKeys.ADD_MEMBER,
          extraDataJSONObject.toString(),
          user.getUserId());
    }
  }
  protected void getRootFolders(CommandArgument argument, Document doc, Element foldersEl)
      throws Exception {

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

    groupParams.put("usersGroups", new Long(argument.getUserId()));

    List<Group> groups =
        GroupLocalServiceUtil.search(
            argument.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

    List<Organization> userOrgs =
        OrganizationLocalServiceUtil.getUserOrganizations(argument.getUserId(), true);

    for (Organization organization : userOrgs) {
      groups.add(0, organization.getGroup());
    }

    if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED
        || PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {

      Group userGroup =
          GroupLocalServiceUtil.getUserGroup(argument.getCompanyId(), argument.getUserId());

      groups.add(0, userGroup);
    }

    ThemeDisplay themeDisplay = argument.getThemeDisplay();

    long scopeGroupId = themeDisplay.getScopeGroupId();

    for (Group group : groups) {
      Element folderEl = doc.createElement("Folder");

      foldersEl.appendChild(folderEl);

      boolean setNameAttribute = false;

      if (group.hasStagingGroup()) {
        Group stagingGroup = group.getStagingGroup();

        if (stagingGroup.getGroupId() == scopeGroupId) {
          folderEl.setAttribute(
              "name",
              stagingGroup.getGroupId()
                  + " - "
                  + HtmlUtil.escape(stagingGroup.getDescriptiveName()));

          setNameAttribute = true;
        }
      }

      if (!setNameAttribute) {
        folderEl.setAttribute(
            "name", group.getGroupId() + " - " + HtmlUtil.escape(group.getDescriptiveName()));
      }
    }
  }
  public static Website addWebsite(Organization organization) throws Exception {

    return WebsiteLocalServiceUtil.addWebsite(
        organization.getUserId(),
        organization.getModelClassName(),
        organization.getOrganizationId(),
        "http://www.test.com",
        _getListTypeId(ListTypeConstants.ORGANIZATION_WEBSITE),
        false,
        new ServiceContext());
  }
  public static EmailAddress addEmailAddress(Organization organization) throws Exception {

    return EmailAddressLocalServiceUtil.addEmailAddress(
        organization.getUserId(),
        organization.getModelClassName(),
        organization.getOrganizationId(),
        "*****@*****.**",
        _getListTypeId(ListTypeConstants.ORGANIZATION_EMAIL_ADDRESS),
        false,
        new ServiceContext());
  }
 public static Phone addPhone(Organization organization) throws Exception {
   return PhoneLocalServiceUtil.addPhone(
       organization.getUserId(),
       organization.getModelClassName(),
       organization.getOrganizationId(),
       "0000000000",
       "000",
       _getListTypeId(ListTypeConstants.ORGANIZATION_PHONE),
       false,
       new ServiceContext());
 }
  public static PasswordPolicy addPasswordPolicyRel(
      Organization organization, ServiceContext serviceContext) throws Exception {

    PasswordPolicy passwordPolicy = PasswordPolicyTestUtil.addPasswordPolicy(serviceContext);

    PasswordPolicyRelLocalServiceUtil.addPasswordPolicyRel(
        passwordPolicy.getPasswordPolicyId(),
        organization.getModelClassName(),
        organization.getOrganizationId());

    return passwordPolicy;
  }
  @Override
  public boolean isChecked(Object obj) {
    Organization organization = (Organization) obj;

    try {
      Group group = organization.getGroup();

      return GroupLocalServiceUtil.hasRoleGroup(_role.getRoleId(), group.getGroupId());
    } catch (Exception e) {
      _log.error(e, e);

      return false;
    }
  }
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      ActionRequest req,
      ActionResponse res)
      throws Exception {

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

    try {
      Organization organization = null;

      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        organization = updateOrganization(req);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteOrganizations(req);
      }

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

      if (organization != null) {
        redirect += organization.getOrganizationId();
      }

      sendRedirect(req, res, redirect);
    } catch (Exception e) {
      if (e instanceof NoSuchOrganizationException || e instanceof PrincipalException) {

        SessionErrors.add(req, e.getClass().getName());

        setForward(req, "portlet.enterprise_admin.error");
      } else if (e instanceof DuplicateOrganizationException
          || e instanceof NoSuchCountryException
          || e instanceof NoSuchListTypeException
          || e instanceof OrganizationNameException
          || e instanceof OrganizationParentException
          || e instanceof RequiredOrganizationException) {

        SessionErrors.add(req, e.getClass().getName());

        if (e instanceof RequiredOrganizationException) {
          res.sendRedirect(ParamUtil.getString(req, "redirect"));
        }
      } else {
        throw e;
      }
    }
  }
Esempio n. 11
0
  protected long[] getAncestorOrganizationIds(long[] organizationIds) throws Exception {

    Set<Long> ancestorOrganizationIds = new HashSet<>();

    for (long organizationId : organizationIds) {
      Organization organization = OrganizationLocalServiceUtil.getOrganization(organizationId);

      for (long ancestorOrganizationId : organization.getAncestorOrganizationIds()) {

        ancestorOrganizationIds.add(ancestorOrganizationId);
      }
    }

    return ArrayUtil.toLongArray(ancestorOrganizationIds);
  }
Esempio n. 12
0
  public long[] getOrganizationIds(boolean includeAdministrative)
      throws PortalException, SystemException {

    List<Organization> organizations = getOrganizations(includeAdministrative);

    long[] organizationIds = new long[organizations.size()];

    for (int i = 0; i < organizations.size(); i++) {
      Organization organization = organizations.get(i);

      organizationIds[i] = organization.getOrganizationId();
    }

    return organizationIds;
  }
Esempio n. 13
0
  public String getOrganizationEntriesRSS(
      long organizationId,
      int max,
      String type,
      double version,
      String displayStyle,
      String feedURL,
      String entryURL)
      throws PortalException, SystemException {

    Organization organization = organizationPersistence.findByPrimaryKey(organizationId);

    String name = organization.getName();

    List blogsEntries = getOrganizationEntries(organizationId, max);

    return exportToRSS(name, null, type, version, displayStyle, feedURL, entryURL, blogsEntries);
  }
  public static Address addAddress(Organization organization) throws Exception {

    return AddressLocalServiceUtil.addAddress(
        organization.getUserId(),
        organization.getModelClassName(),
        organization.getOrganizationId(),
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        RandomTestUtil.nextLong(),
        RandomTestUtil.randomLong(),
        _getListTypeId(ListTypeConstants.ORGANIZATION_ADDRESS),
        false,
        false,
        new ServiceContext());
  }
Esempio n. 15
0
 public List<TtUser> getUsersForRole(String roleName, long userId) {
   List<TtUser> roleUsrs = new ArrayList<TtUser>();
   try {
     List<Organization> usrOrgs = orgService.getUserOrganizations(userId);
     for (Organization org : usrOrgs) {
       Role role = roleService.getRole(org.getCompanyId(), roleName);
       if (role != null) {
         List<User> usrs = usrService.getRoleUsers(role.getRoleId());
         for (User usr : usrs) {
           roleUsrs.add(UserServiceConversionHelper.convertPortalUserToTtUser(usr));
         }
       }
     }
   } catch (PortalException ex) {
     Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
   } catch (SystemException ex) {
     Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
   }
   return roleUsrs;
 }
  public int compareTo(Organization organization) {
    int value = 0;

    value = getName().compareTo(organization.getName());

    if (value != 0) {
      return value;
    }

    return 0;
  }
  public static Organization addSite(Organization organization) throws Exception {

    return OrganizationLocalServiceUtil.updateOrganization(
        organization.getCompanyId(),
        organization.getOrganizationId(),
        organization.getParentOrganizationId(),
        organization.getName(),
        organization.getType(),
        organization.getRegionId(),
        organization.getCountryId(),
        organization.getStatusId(),
        organization.getComments(),
        false,
        null,
        true,
        null);
  }
Esempio n. 18
0
  private static boolean _isEntityRank(
      long companyId, MBStatsUser statsUser, String entityType, String entityValue)
      throws Exception {

    long groupId = statsUser.getGroupId();
    long userId = statsUser.getUserId();

    if (entityType.equals("organization-role") || entityType.equals("site-role")) {

      Role role = RoleLocalServiceUtil.getRole(companyId, entityValue);

      if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(userId, groupId, role.getRoleId(), true)) {

        return true;
      }
    } else if (entityType.equals("organization")) {
      Organization organization =
          OrganizationLocalServiceUtil.getOrganization(companyId, entityValue);

      if (OrganizationLocalServiceUtil.hasUserOrganization(
          userId, organization.getOrganizationId(), false, false)) {

        return true;
      }
    } else if (entityType.equals("regular-role")) {
      if (RoleLocalServiceUtil.hasUserRole(userId, companyId, entityValue, true)) {

        return true;
      }
    } else if (entityType.equals("user-group")) {
      UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(companyId, entityValue);

      if (UserLocalServiceUtil.hasUserGroupUser(userGroup.getUserGroupId(), userId)) {

        return true;
      }
    }

    return false;
  }
Esempio n. 19
0
  public Set<String> getReminderQueryQuestions() throws PortalException, SystemException {

    Set<String> questions = new TreeSet<String>();

    List<Organization> organizations =
        OrganizationLocalServiceUtil.getUserOrganizations(getUserId());

    for (Organization organization : organizations) {
      Set<String> organizationQuestions = organization.getReminderQueryQuestions(getLanguageId());

      if (organizationQuestions.size() == 0) {
        Organization parentOrganization = organization.getParentOrganization();

        while ((organizationQuestions.size() == 0) && (parentOrganization != null)) {

          organizationQuestions = parentOrganization.getReminderQueryQuestions(getLanguageId());

          parentOrganization = parentOrganization.getParentOrganization();
        }
      }

      questions.addAll(organizationQuestions);
    }

    if (questions.size() == 0) {
      Set<String> defaultQuestions =
          SetUtil.fromArray(PropsUtil.getArray(PropsKeys.USERS_REMINDER_QUERIES_QUESTIONS));

      questions.addAll(defaultQuestions);
    }

    return questions;
  }
  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }

    Organization organization = null;

    try {
      organization = (Organization) obj;
    } catch (ClassCastException cce) {
      return false;
    }

    long primaryKey = organization.getPrimaryKey();

    if (getPrimaryKey() == primaryKey) {
      return true;
    } else {
      return false;
    }
  }
  @Override
  protected String getExportPortletPreferencesUuid(
      PortletDataContext portletDataContext, Portlet portlet, String className, long primaryKeyLong)
      throws Exception {

    String uuid = null;

    Element rootElement = portletDataContext.getExportDataRootElement();

    if (className.equals(Organization.class.getName())) {
      Organization organization = _organizationLocalService.fetchOrganization(primaryKeyLong);

      if (organization != null) {
        uuid = organization.getUuid();

        portletDataContext.addReferenceElement(
            portlet, rootElement, organization, PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
      }
    }

    return uuid;
  }
  private void _buildParentGroupsBreadcrumb(
      LayoutSet layoutSet, PortletURL portletURL, ThemeDisplay themeDisplay, StringBundler sb)
      throws Exception {
    Group group = layoutSet.getGroup();

    if (group.isOrganization()) {
      Organization organization =
          OrganizationLocalServiceUtil.getOrganization(group.getOrganizationId());

      Organization parentOrganization = organization.getParentOrganization();

      if (parentOrganization != null) {
        Group parentGroup = parentOrganization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    } else if (group.isUser()) {
      User groupUser = UserLocalServiceUtil.getUser(group.getClassPK());

      List<Organization> organizations =
          OrganizationLocalServiceUtil.getUserOrganizations(groupUser.getUserId(), true);

      if (!organizations.isEmpty()) {
        Organization organization = organizations.get(0);

        Group parentGroup = organization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    }

    int layoutsPageCount = 0;

    if (layoutSet.isPrivateLayout()) {
      layoutsPageCount = group.getPrivateLayoutsPageCount();
    } else {
      layoutsPageCount = group.getPublicLayoutsPageCount();
    }

    if ((layoutsPageCount > 0) && !group.getName().equals(GroupConstants.GUEST)) {
      String layoutSetFriendlyURL = PortalUtil.getLayoutSetFriendlyURL(layoutSet, themeDisplay);

      sb.append("<li><span><a href=\"");
      sb.append(layoutSetFriendlyURL);
      sb.append("\">");
      sb.append(HtmlUtil.escape(group.getDescriptiveName()));
      sb.append("</a></span></li>");
    }
  }
  public static OrgLabor addOrgLabor(Organization organization) throws Exception {

    return OrgLaborLocalServiceUtil.addOrgLabor(
        organization.getOrganizationId(),
        _getListTypeId(ListTypeConstants.ORGANIZATION_SERVICE),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt(),
        RandomTestUtil.nextInt());
  }
  protected void setJoin(QueryPos qPos, LinkedHashMap<String, Object> params) {

    if (params == null) {
      return;
    }

    for (Map.Entry<String, Object> entry : params.entrySet()) {
      String key = entry.getKey();

      if (key.equals("expandoAttributes")) {
        continue;
      }

      Object value = entry.getValue();

      if (key.equals("usersOrgsTree")) {
        List<Organization> organizationsTree = (List<Organization>) value;

        if (!organizationsTree.isEmpty()) {
          for (Organization organization : organizationsTree) {
            StringBundler treePath = new StringBundler(5);

            treePath.append(StringPool.PERCENT);
            treePath.append(StringPool.SLASH);
            treePath.append(organization.getOrganizationId());
            treePath.append(StringPool.SLASH);
            treePath.append(StringPool.PERCENT);

            qPos.add(treePath.toString());
          }
        }
      } else if (value instanceof Long) {
        Long valueLong = (Long) value;

        if (Validator.isNotNull(valueLong)) {
          qPos.add(valueLong);
        }
      } else if (value instanceof Long[]) {
        Long[] valueArray = (Long[]) value;

        for (Long element : valueArray) {
          if (Validator.isNotNull(element)) {
            qPos.add(element);
          }
        }
      } else if (value instanceof Long[][]) {
        Long[][] valueDoubleArray = (Long[][]) value;

        for (Long[] valueArray : valueDoubleArray) {
          for (Long valueLong : valueArray) {
            qPos.add(valueLong);
          }
        }
      } else if (value instanceof String) {
        String valueString = (String) value;

        if (Validator.isNotNull(valueString)) {
          qPos.add(valueString);
        }
      } else if (value instanceof String[]) {
        String[] valueArray = (String[]) value;

        for (String element : valueArray) {
          if (Validator.isNotNull(element)) {
            qPos.add(element);
          }
        }
      } else if (value instanceof CustomSQLParam) {
        CustomSQLParam customSQLParam = (CustomSQLParam) value;

        customSQLParam.process(qPos);
      }
    }
  }
  @Override
  public void processAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

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

    try {
      Organization organization = null;

      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        organization = updateOrganization(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteOrganizations(actionRequest);
      }

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

      if (organization != null) {
        redirect =
            HttpUtil.setParameter(
                redirect,
                actionResponse.getNamespace() + "organizationId",
                organization.getOrganizationId());
      }

      sendRedirect(actionRequest, actionResponse, redirect);
    } catch (Exception e) {
      if (e instanceof NoSuchOrganizationException || e instanceof PrincipalException) {

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

        setForward(actionRequest, "portlet.users_admin.error");
      } else if (e instanceof AddressCityException
          || e instanceof AddressStreetException
          || e instanceof AddressZipException
          || e instanceof DuplicateOrganizationException
          || e instanceof EmailAddressException
          || e instanceof NoSuchCountryException
          || e instanceof NoSuchListTypeException
          || e instanceof NoSuchRegionException
          || e instanceof OrganizationNameException
          || e instanceof OrganizationParentException
          || e instanceof PhoneNumberException
          || e instanceof RequiredOrganizationException
          || e instanceof WebsiteURLException) {

        if (e instanceof NoSuchListTypeException) {
          NoSuchListTypeException nslte = (NoSuchListTypeException) e;

          SessionErrors.add(actionRequest, e.getClass().getName() + nslte.getType());
        } else {
          SessionErrors.add(actionRequest, e.getClass());
        }

        if (e instanceof RequiredOrganizationException) {
          String redirect =
              PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

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

          if (organizationId > 0) {
            redirect =
                HttpUtil.setParameter(
                    redirect, actionResponse.getNamespace() + "organizationId", organizationId);
          }

          if (Validator.isNotNull(redirect)) {
            actionResponse.sendRedirect(redirect);
          }
        }
      } else {
        throw e;
      }
    }
  }
  @Override
  public String getDescriptiveName(Locale locale) throws PortalException {
    Group curGroup = this;

    String name = getName(locale);

    if (Validator.isNull(name)) {
      Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(getGroupId());

      name = getName(siteDefaultLocale);
    }

    if (isCompany() && !isCompanyStagingGroup()) {
      name = LanguageUtil.get(locale, "global");
    } else if (isControlPanel()) {
      name = LanguageUtil.get(locale, "control-panel");
    } else if (isGuest()) {
      Company company = CompanyLocalServiceUtil.getCompany(getCompanyId());

      Account account = company.getAccount();

      name = account.getName();
    } else if (isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(getClassPK());

      name = layout.getName(locale);
    } else if (isLayoutPrototype()) {
      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(getClassPK());

      name = layoutPrototype.getName(locale);
    } else if (isLayoutSetPrototype()) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(getClassPK());

      name = layoutSetPrototype.getName(locale);
    } else if (isOrganization()) {
      long organizationId = getOrganizationId();

      Organization organization = OrganizationLocalServiceUtil.getOrganization(organizationId);

      name = organization.getName();

      curGroup = organization.getGroup();
    } else if (isUser()) {
      long userId = getClassPK();

      User user = UserLocalServiceUtil.getUser(userId);

      name = user.getFullName();
    } else if (isUserGroup()) {
      long userGroupId = getClassPK();

      UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(userGroupId);

      name = userGroup.getName();
    } else if (isUserPersonalSite()) {
      name = LanguageUtil.get(locale, "user-personal-site");
    }

    if (curGroup.isStaged() && !curGroup.isStagedRemotely() && curGroup.isStagingGroup()) {

      Group liveGroup = getLiveGroup();

      name = liveGroup.getDescriptiveName(locale);
    }

    return name;
  }
  protected boolean isViewableGroup(
      PermissionChecker permissionChecker,
      Layout layout,
      String controlPanelCategory,
      boolean checkResourcePermission)
      throws PortalException, SystemException {

    Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());

    // Inactive sites are not viewable

    if (!group.isActive()) {
      return false;
    } else if (group.isStagingGroup()) {
      Group liveGroup = group.getLiveGroup();

      if (!liveGroup.isActive()) {
        return false;
      }
    }

    // User private layouts are only viewable by the user and anyone who can
    // update the user. The user must also be active.

    if (group.isUser()) {
      long groupUserId = group.getClassPK();

      if (groupUserId == permissionChecker.getUserId()) {
        return true;
      }

      User groupUser = UserLocalServiceUtil.getUserById(groupUserId);

      if (!groupUser.isActive()) {
        return false;
      }

      if (layout.isPrivateLayout()) {
        if (GroupPermissionUtil.contains(
                permissionChecker, groupUser.getGroupId(), ActionKeys.MANAGE_LAYOUTS)
            || UserPermissionUtil.contains(
                permissionChecker,
                groupUserId,
                groupUser.getOrganizationIds(),
                ActionKeys.UPDATE)) {

          return true;
        }

        return false;
      }
    }

    // If the current group is staging, only users with editorial rights
    // can access it

    if (group.isStagingGroup()) {
      if (GroupPermissionUtil.contains(
          permissionChecker, group.getGroupId(), ActionKeys.VIEW_STAGING)) {

        return true;
      }

      return false;
    }

    // Control panel layouts are only viewable by authenticated users

    if (group.isControlPanel()) {
      if (!permissionChecker.isSignedIn()) {
        return false;
      }

      if (PortalPermissionUtil.contains(permissionChecker, ActionKeys.VIEW_CONTROL_PANEL)) {

        return true;
      }

      if (Validator.isNotNull(controlPanelCategory)) {
        return true;
      }

      return false;
    }

    // Site layouts are only viewable by users who are members of the site
    // or by users who can update the site

    if (group.isSite()) {
      if (GroupPermissionUtil.contains(
              permissionChecker, group.getGroupId(), ActionKeys.MANAGE_LAYOUTS)
          || GroupPermissionUtil.contains(
              permissionChecker, group.getGroupId(), ActionKeys.UPDATE)) {

        return true;
      }

      if (layout.isPrivateLayout() && !permissionChecker.isGroupMember(group.getGroupId())) {

        return false;
      }
    }

    // Organization site layouts are also viewable by users who belong to
    // the organization or by users who can update organization

    if (group.isCompany()) {
      return false;
    } else if (group.isLayoutPrototype()) {
      if (LayoutPrototypePermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.VIEW)) {

        return true;
      }

      return false;
    } else if (group.isLayoutSetPrototype()) {
      if (LayoutSetPrototypePermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.VIEW)) {

        return true;
      }

      return false;
    } else if (group.isOrganization()) {
      long organizationId = group.getOrganizationId();

      if (OrganizationLocalServiceUtil.hasUserOrganization(
          permissionChecker.getUserId(), organizationId, false, false)) {

        return true;
      } else if (OrganizationPermissionUtil.contains(
          permissionChecker, organizationId, ActionKeys.UPDATE)) {

        return true;
      }

      if (!PropsValues.ORGANIZATIONS_MEMBERSHIP_STRICT) {
        List<Organization> userOrgs =
            OrganizationLocalServiceUtil.getUserOrganizations(permissionChecker.getUserId());

        for (Organization organization : userOrgs) {
          for (Organization ancestorOrganization : organization.getAncestors()) {

            if (organizationId == ancestorOrganization.getOrganizationId()) {

              return true;
            }
          }
        }
      }
    } else if (group.isUserGroup()) {
      if (UserGroupPermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.UPDATE)) {

        return true;
      }
    }

    // Only check the actual Layout if all of the above failed

    if (containsWithoutViewableGroup(
        permissionChecker, layout, controlPanelCategory, ActionKeys.VIEW)) {

      return true;
    }

    // As a last resort, check if any top level pages are viewable by the
    // user

    List<Layout> layouts =
        LayoutLocalServiceUtil.getLayouts(
            layout.getGroupId(),
            layout.isPrivateLayout(),
            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

    for (Layout curLayout : layouts) {
      if (!curLayout.isHidden()
          && containsWithoutViewableGroup(
              permissionChecker, curLayout, controlPanelCategory, ActionKeys.VIEW)) {

        return true;
      }
    }

    return false;
  }
Esempio n. 28
0
  public int countByC_FN_MN_LN_SN_EA_S(
      long companyId,
      String[] firstNames,
      String[] middleNames,
      String[] lastNames,
      String[] screenNames,
      String[] emailAddresses,
      int status,
      LinkedHashMap<String, Object> params,
      boolean andOperator)
      throws SystemException {

    firstNames = CustomSQLUtil.keywords(firstNames);
    middleNames = CustomSQLUtil.keywords(middleNames);
    lastNames = CustomSQLUtil.keywords(lastNames);
    screenNames = CustomSQLUtil.keywords(screenNames);
    emailAddresses = CustomSQLUtil.keywords(emailAddresses);

    if (params == null) {
      params = _emptyLinkedHashMap;
    }

    Long[] groupIds = null;

    if (params.get("usersGroups") instanceof Long) {
      Long groupId = (Long) params.get("usersGroups");

      if (groupId > 0) {
        groupIds = new Long[] {groupId};
      }
    } else {
      groupIds = (Long[]) params.get("usersGroups");
    }

    boolean inherit = GetterUtil.getBoolean(params.get("inherit"));

    boolean doUnion = Validator.isNotNull(groupIds) && inherit;

    LinkedHashMap<String, Object> params1 = params;

    LinkedHashMap<String, Object> params2 = null;

    LinkedHashMap<String, Object> params3 = null;

    if (doUnion) {
      params2 = new LinkedHashMap<String, Object>(params1);

      params2.remove("usersGroups");

      params3 = new LinkedHashMap<String, Object>(params1);

      params3.remove("usersGroups");

      List<Long> organizationIds = new ArrayList<Long>();
      List<Long> userGroupIds = new ArrayList<Long>();

      for (long groupId : groupIds) {
        Group group = GroupLocalServiceUtil.fetchGroup(groupId);

        if ((group != null) && group.isOrganization()) {
          organizationIds.add(group.getOrganizationId());
        }

        List<Organization> organizations = GroupUtil.getOrganizations(groupId);

        for (Organization organization : organizations) {
          organizationIds.add(organization.getOrganizationId());
        }

        List<UserGroup> userGroups = GroupUtil.getUserGroups(groupId);

        for (int i = 0; i < userGroups.size(); i++) {
          UserGroup userGroup = userGroups.get(i);

          userGroupIds.add(userGroup.getUserGroupId());
        }
      }

      params2.put("usersOrgs", organizationIds.toArray(new Long[organizationIds.size()]));

      params3.put("usersUserGroups", userGroupIds.toArray(new Long[userGroupIds.size()]));
    }

    Session session = null;

    try {
      session = openSession();

      Set<Long> userIds = new HashSet<Long>();

      userIds.addAll(
          countByC_FN_MN_LN_SN_EA_S(
              session,
              companyId,
              firstNames,
              middleNames,
              lastNames,
              screenNames,
              emailAddresses,
              status,
              params1,
              andOperator));

      if (doUnion) {
        userIds.addAll(
            countByC_FN_MN_LN_SN_EA_S(
                session,
                companyId,
                firstNames,
                middleNames,
                lastNames,
                screenNames,
                emailAddresses,
                status,
                params2,
                andOperator));

        userIds.addAll(
            countByC_FN_MN_LN_SN_EA_S(
                session,
                companyId,
                firstNames,
                middleNames,
                lastNames,
                screenNames,
                emailAddresses,
                status,
                params3,
                andOperator));
      }

      return userIds.size();
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
Esempio n. 29
0
  public List<User> findByC_FN_MN_LN_SN_EA_S(
      long companyId,
      String[] firstNames,
      String[] middleNames,
      String[] lastNames,
      String[] screenNames,
      String[] emailAddresses,
      int status,
      LinkedHashMap<String, Object> params,
      boolean andOperator,
      int start,
      int end,
      OrderByComparator obc)
      throws SystemException {

    firstNames = CustomSQLUtil.keywords(firstNames);
    middleNames = CustomSQLUtil.keywords(middleNames);
    lastNames = CustomSQLUtil.keywords(lastNames);
    screenNames = CustomSQLUtil.keywords(screenNames);
    emailAddresses = CustomSQLUtil.keywords(emailAddresses);

    if (params == null) {
      params = _emptyLinkedHashMap;
    }

    Long[] groupIds = null;

    if (params.get("usersGroups") instanceof Long) {
      Long groupId = (Long) params.get("usersGroups");

      if (groupId > 0) {
        groupIds = new Long[] {groupId};
      }
    } else {
      groupIds = (Long[]) params.get("usersGroups");
    }

    boolean inherit = GetterUtil.getBoolean(params.get("inherit"));

    boolean doUnion = Validator.isNotNull(groupIds) && inherit;

    LinkedHashMap<String, Object> params1 = params;

    LinkedHashMap<String, Object> params2 = null;

    LinkedHashMap<String, Object> params3 = null;

    if (doUnion) {
      params2 = new LinkedHashMap<String, Object>(params1);

      params2.remove("usersGroups");

      params3 = new LinkedHashMap<String, Object>(params1);

      params3.remove("usersGroups");

      List<Long> organizationIds = new ArrayList<Long>();
      List<Long> userGroupIds = new ArrayList<Long>();

      for (long groupId : groupIds) {
        Group group = GroupLocalServiceUtil.fetchGroup(groupId);

        if ((group != null) && group.isOrganization()) {
          organizationIds.add(group.getOrganizationId());
        }

        List<Organization> organizations = GroupUtil.getOrganizations(groupId);

        for (Organization organization : organizations) {
          organizationIds.add(organization.getOrganizationId());
        }

        List<UserGroup> userGroups = GroupUtil.getUserGroups(groupId);

        for (int i = 0; i < userGroups.size(); i++) {
          UserGroup userGroup = userGroups.get(i);

          userGroupIds.add(userGroup.getUserGroupId());
        }
      }

      params2.put("usersOrgs", organizationIds.toArray(new Long[organizationIds.size()]));

      params3.put("usersUserGroups", userGroupIds.toArray(new Long[userGroupIds.size()]));
    }

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(FIND_BY_C_FN_MN_LN_SN_EA_S);

      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.firstName)", StringPool.LIKE, false, firstNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.middleName)", StringPool.LIKE, false, middleNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.lastName)", StringPool.LIKE, false, lastNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.screenName)", StringPool.LIKE, false, screenNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.emailAddress)", StringPool.LIKE, true, emailAddresses);

      if (status == WorkflowConstants.STATUS_ANY) {
        sql = StringUtil.replace(sql, _STATUS_SQL, StringPool.BLANK);
      }

      StringBundler sb = new StringBundler();

      sb.append(StringPool.OPEN_PARENTHESIS);
      sb.append(replaceJoinAndWhere(sql, params1));
      sb.append(StringPool.CLOSE_PARENTHESIS);

      if (doUnion) {
        sb.append(" UNION (");
        sb.append(replaceJoinAndWhere(sql, params2));
        sb.append(") UNION (");
        sb.append(replaceJoinAndWhere(sql, params3));
        sb.append(StringPool.CLOSE_PARENTHESIS);
      }

      if (obc != null) {
        sb.append(" ORDER BY ");
        sb.append(obc.toString());
      }

      sql = sb.toString();

      sql = CustomSQLUtil.replaceAndOperator(sql, andOperator);

      SQLQuery q = session.createSQLQuery(sql);

      q.addScalar("userId", Type.LONG);

      QueryPos qPos = QueryPos.getInstance(q);

      setJoin(qPos, params1);

      qPos.add(companyId);
      qPos.add(false);
      qPos.add(firstNames, 2);
      qPos.add(middleNames, 2);
      qPos.add(lastNames, 2);
      qPos.add(screenNames, 2);
      qPos.add(emailAddresses, 2);

      if (status != WorkflowConstants.STATUS_ANY) {
        qPos.add(status);
      }

      if (doUnion) {
        setJoin(qPos, params2);

        qPos.add(companyId);
        qPos.add(false);
        qPos.add(firstNames, 2);
        qPos.add(middleNames, 2);
        qPos.add(lastNames, 2);
        qPos.add(screenNames, 2);
        qPos.add(emailAddresses, 2);

        if (status != WorkflowConstants.STATUS_ANY) {
          qPos.add(status);
        }

        setJoin(qPos, params3);

        qPos.add(companyId);
        qPos.add(false);
        qPos.add(firstNames, 2);
        qPos.add(middleNames, 2);
        qPos.add(lastNames, 2);
        qPos.add(screenNames, 2);
        qPos.add(emailAddresses, 2);

        if (status != WorkflowConstants.STATUS_ANY) {
          qPos.add(status);
        }
      }

      List<Long> userIds = (List<Long>) QueryUtil.list(q, getDialect(), start, end);

      List<User> users = new ArrayList<User>(userIds.size());

      for (Long userId : userIds) {
        User user = UserUtil.findByPrimaryKey(userId);

        users.add(user);
      }

      return users;
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  @Override
  public List<Group> getUserSitesGroups() throws PortalException {
    try {
      User user = getUser();

      List<Group> groups = new ArrayList<>();

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

      groupParams.put("active", true);
      groupParams.put("usersGroups", user.getUserId());

      List<Group> userSiteGroups =
          groupLocalService.search(
              user.getCompanyId(), null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

      for (Group userSiteGroup : userSiteGroups) {
        if (SyncUtil.isSyncEnabled(userSiteGroup)) {
          userSiteGroup.setName(userSiteGroup.getDescriptiveName());

          groups.add(userSiteGroup);
        }
      }

      List<Organization> organizations =
          organizationLocalService.getOrganizations(
              user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);

      for (Organization organization : organizations) {
        Group userOrganizationGroup = organization.getGroup();

        if (SyncUtil.isSyncEnabled(userOrganizationGroup)) {
          groups.add(userOrganizationGroup);
        }

        if (!GetterUtil.getBoolean(PropsUtil.get(PropsKeys.ORGANIZATIONS_MEMBERSHIP_STRICT))) {

          for (Organization ancestorOrganization : organization.getAncestors()) {

            Group userAncestorOrganizationGroup = ancestorOrganization.getGroup();

            if (SyncUtil.isSyncEnabled(userAncestorOrganizationGroup)) {

              groups.add(userAncestorOrganizationGroup);
            }
          }
        }
      }

      if (PrefsPropsUtil.getBoolean(
          user.getCompanyId(),
          PortletPropsKeys.SYNC_ALLOW_USER_PERSONAL_SITES,
          PortletPropsValues.SYNC_ALLOW_USER_PERSONAL_SITES)) {

        groups.add(user.getGroup());
      }

      Collections.sort(groups, new GroupNameComparator());

      return ListUtil.unique(groups);
    } catch (PortalException pe) {
      throw new PortalException(pe.getClass().getName(), pe);
    }
  }