public void initPermissions(List<Company> companies, Portlet portlet) {
    String rootPortletId = portlet.getRootPortletId();

    for (Company company : companies) {
      long companyId = company.getCompanyId();

      Role powerUserRole = getPowerUserRole(companyId);

      if (powerUserRole == null) {
        continue;
      }

      Group userPersonalSiteGroup = getUserPersonalSiteGroup(companyId);

      if (userPersonalSiteGroup == null) {
        continue;
      }

      try {
        initPermissions(
            companyId,
            powerUserRole.getRoleId(),
            rootPortletId,
            userPersonalSiteGroup.getGroupId());
      } catch (PortalException pe) {
        _log.error(
            "Unable to initialize user personal site permissions "
                + "for portlet "
                + portlet.getPortletId()
                + " in company "
                + companyId,
            pe);
      }
    }
  }
  @Override
  protected String[] doLogin(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    long companyId = PortalUtil.getCompanyId(request);

    if (!isEnabled(companyId)) {
      return null;
    }

    String login = ParamUtil.getString(request, getLoginParam());

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

    String password = ParamUtil.getString(request, getPasswordParam());

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

    Company company = PortalUtil.getCompany(request);

    String authType = company.getAuthType();

    long userId = 0;

    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
      userId = _userLocalService.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
      userId = _userLocalService.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
      userId = GetterUtil.getLong(login);
    } else {
      return null;
    }

    if (userId > 0) {
      User user = _userLocalService.getUserById(userId);

      String userPassword = user.getPassword();

      if (!user.isPasswordEncrypted()) {
        userPassword = PasswordEncryptorUtil.encrypt(userPassword);
      }

      String encPassword = PasswordEncryptorUtil.encrypt(password, userPassword);

      if (!userPassword.equals(password) && !userPassword.equals(encPassword)) {

        return null;
      }
    }

    String[] credentials =
        new String[] {String.valueOf(userId), password, Boolean.FALSE.toString()};

    return credentials;
  }
  protected void updateJournalArticles() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer()) {
      List<Company> companies = _companyLocalService.getCompanies();

      for (Company company : companies) {
        updateJournalArticles(company.getCompanyId());
      }
    }
  }
  protected void updateArticleType() throws Exception {
    if (!hasSelectedArticleTypes()) {
      return;
    }

    List<String> types = getArticleTypes();

    if (types.size() <= 0) {
      return;
    }

    Locale localeThreadLocalDefaultLocale = LocaleThreadLocal.getDefaultLocale();

    try {
      List<Company> companies = _companyLocalService.getCompanies();

      for (Company company : companies) {
        LocaleThreadLocal.setDefaultLocale(company.getLocale());

        Set<Locale> locales = LanguageUtil.getAvailableLocales(company.getGroupId());

        Locale defaultLocale =
            LocaleUtil.fromLanguageId(
                UpgradeProcessUtil.getDefaultLanguageId(company.getCompanyId()));

        Map<Locale, String> nameMap =
            LocalizationUtil.getLocalizationMap(locales, defaultLocale, "type");

        AssetVocabulary assetVocabulary =
            addAssetVocabulary(
                company.getGroupId(),
                company.getCompanyId(),
                "type",
                nameMap,
                new HashMap<Locale, String>());

        Map<String, Long> journalArticleTypesToAssetCategoryIds = new HashMap<>();

        for (String type : types) {
          AssetCategory assetCategory =
              addAssetCategory(
                  company.getGroupId(),
                  company.getCompanyId(),
                  type,
                  assetVocabulary.getVocabularyId());

          journalArticleTypesToAssetCategoryIds.put(type, assetCategory.getCategoryId());
        }

        updateArticles(company.getCompanyId(), journalArticleTypesToAssetCategoryIds);
      }
    } finally {
      LocaleThreadLocal.setDefaultLocale(localeThreadLocalDefaultLocale);
    }
  }
  protected void sendRedirect(
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      ThemeDisplay themeDisplay,
      User user,
      String password)
      throws Exception {

    String login = null;

    Company company = themeDisplay.getCompany();

    String authType = company.getAuthType();

    if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
      login = String.valueOf(user.getUserId());
    } else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
      login = user.getScreenName();
    } else {
      login = user.getEmailAddress();
    }

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

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

    if (Validator.isNotNull(redirect)) {
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      AuthenticatedSessionManagerUtil.login(request, response, login, password, false, null);
    } else {
      PortletURL loginURL = LoginUtil.getLoginURL(request, themeDisplay.getPlid());

      loginURL.setParameter("login", login);

      redirect = loginURL.toString();
    }

    actionResponse.sendRedirect(redirect);
  }
  public GroupSearch getGroupSearch() throws Exception {
    ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

    Company company = themeDisplay.getCompany();

    GroupSearch groupSearch = new GroupSearch(_liferayPortletRequest, getPortletURL());

    GroupSearchTerms groupSearchTerms = (GroupSearchTerms) groupSearch.getSearchTerms();

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

    int additionalSites = 0;
    int total = 0;

    boolean includeCompany = ParamUtil.getBoolean(_request, "includeCompany");
    boolean includeUserPersonalSite = ParamUtil.getBoolean(_request, "includeUserPersonalSite");

    long[] classNameIds = _CLASS_NAME_IDS;

    if (includeCompany) {
      classNameIds = ArrayUtil.append(classNameIds, PortalUtil.getClassNameId(Company.class));
    }

    if (includeUserPersonalSite) {
      if (groupSearch.getStart() == 0) {
        Group userPersonalSite =
            GroupLocalServiceUtil.getGroup(
                company.getCompanyId(), GroupConstants.USER_PERSONAL_SITE);

        results.add(userPersonalSite);
      }

      additionalSites++;
    }

    String type = getType();

    if (type.equals("layoutScopes")) {
      total =
          GroupLocalServiceUtil.getGroupsCount(
              themeDisplay.getCompanyId(), Layout.class.getName(), getGroupId());
    } else if (type.equals("parent-sites")) {
    } else {
      total =
          GroupLocalServiceUtil.searchCount(
              themeDisplay.getCompanyId(),
              classNameIds,
              groupSearchTerms.getKeywords(),
              getGroupParams());
    }

    total += additionalSites;

    groupSearch.setTotal(total);

    int start = groupSearch.getStart();

    if (groupSearch.getStart() > additionalSites) {
      start = groupSearch.getStart() - additionalSites;
    }

    int end = groupSearch.getEnd() - additionalSites;

    List<Group> groups = null;

    if (type.equals("layoutScopes")) {
      groups =
          GroupLocalServiceUtil.getGroups(
              company.getCompanyId(), Layout.class.getName(), getGroupId(), start, end);

      groups = _filterLayoutGroups(groups, isPrivateLayout());
    } else if (type.equals("parent-sites")) {
      Group group = GroupLocalServiceUtil.getGroup(getGroupId());

      groups = group.getAncestors();

      String filter = getFilter();

      if (Validator.isNotNull(filter)) {
        groups = _filterGroups(groups, filter);
      }

      total = groups.size();

      total += additionalSites;

      groupSearch.setTotal(total);
    } else {
      groups =
          GroupLocalServiceUtil.search(
              company.getCompanyId(),
              classNameIds,
              groupSearchTerms.getKeywords(),
              getGroupParams(),
              start,
              end,
              groupSearch.getOrderByComparator());
    }

    results.addAll(groups);

    groupSearch.setResults(results);

    return groupSearch;
  }
  protected void addUser(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    HttpSession session = request.getSession();

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

    Company company = themeDisplay.getCompany();

    boolean autoPassword = true;
    String password1 = null;
    String password2 = null;
    boolean autoScreenName = isAutoScreenName();
    String screenName = ParamUtil.getString(actionRequest, "screenName");
    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
    long facebookId = ParamUtil.getLong(actionRequest, "facebookId");
    String openId = ParamUtil.getString(actionRequest, "openId");
    String languageId = ParamUtil.getString(actionRequest, "languageId");
    String firstName = ParamUtil.getString(actionRequest, "firstName");
    String middleName = ParamUtil.getString(actionRequest, "middleName");
    String lastName = ParamUtil.getString(actionRequest, "lastName");
    long prefixId = ParamUtil.getInteger(actionRequest, "prefixId");
    long suffixId = ParamUtil.getInteger(actionRequest, "suffixId");
    boolean male = ParamUtil.getBoolean(actionRequest, "male", true);
    int birthdayMonth = ParamUtil.getInteger(actionRequest, "birthdayMonth");
    int birthdayDay = ParamUtil.getInteger(actionRequest, "birthdayDay");
    int birthdayYear = ParamUtil.getInteger(actionRequest, "birthdayYear");
    String jobTitle = ParamUtil.getString(actionRequest, "jobTitle");
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = true;

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

    if (PropsValues.LOGIN_CREATE_ACCOUNT_ALLOW_CUSTOM_PASSWORD) {
      autoPassword = false;

      password1 = ParamUtil.getString(actionRequest, "password1");
      password2 = ParamUtil.getString(actionRequest, "password2");
    }

    boolean openIdPending = false;

    Boolean openIdLoginPending = (Boolean) session.getAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);

    if ((openIdLoginPending != null)
        && openIdLoginPending.booleanValue()
        && Validator.isNotNull(openId)) {

      sendEmail = false;
      openIdPending = true;
    }

    User user =
        _userService.addUserWithWorkflow(
            company.getCompanyId(),
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            facebookId,
            openId,
            LocaleUtil.fromLanguageId(languageId),
            firstName,
            middleName,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            groupIds,
            organizationIds,
            roleIds,
            userGroupIds,
            sendEmail,
            serviceContext);

    if (openIdPending) {
      session.setAttribute(WebKeys.OPEN_ID_LOGIN, Long.valueOf(user.getUserId()));

      session.removeAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);
    } else {

      // Session messages

      if (user.getStatus() == WorkflowConstants.STATUS_APPROVED) {
        SessionMessages.add(request, "userAdded", user.getEmailAddress());
        SessionMessages.add(request, "userAddedPassword", user.getPasswordUnencrypted());
      } else {
        SessionMessages.add(request, "userPending", user.getEmailAddress());
      }
    }

    // Send redirect

    sendRedirect(actionRequest, actionResponse, themeDisplay, user, user.getPasswordUnencrypted());
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    Company company = themeDisplay.getCompany();

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

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

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

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

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

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

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

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

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

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

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

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

      sendRedirect(actionRequest, actionResponse, redirect);
    } catch (NoSuchLayoutException nsle) {
    }
  }
  public GroupSearch getGroupSearch(PortletRequest portletRequest, PortletURL portletURL)
      throws PortalException {

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

    GroupSearch groupSearch = new GroupSearch(portletRequest, portletURL);

    GroupSearchTerms searchTerms = (GroupSearchTerms) groupSearch.getSearchTerms();

    if (!searchTerms.isSearch()) {
      groupSearch.setEmptyResultsMessageCssClass("taglib-empty-result-message-header-has-plus-btn");
    } else {
      groupSearch.setSearch(true);
    }

    long parentGroupId = getParentGroupId(portletRequest);

    Company company = themeDisplay.getCompany();

    List results = null;

    if (!searchTerms.hasSearchTerms()
        && isFilterManageableGroups(portletRequest)
        && (parentGroupId <= 0)) {

      List<Group> groups = getAllGroups(portletRequest);

      groupSearch.setTotal(groups.size());

      results = ListUtil.subList(groups, groupSearch.getStart(), groupSearch.getEnd());
    } else if (searchTerms.hasSearchTerms()) {
      int total =
          _groupLocalService.searchCount(
              company.getCompanyId(),
              _classNameIds,
              searchTerms.getKeywords(),
              getGroupParams(portletRequest, searchTerms, parentGroupId));

      groupSearch.setTotal(total);

      results =
          _groupLocalService.search(
              company.getCompanyId(),
              _classNameIds,
              searchTerms.getKeywords(),
              getGroupParams(portletRequest, searchTerms, parentGroupId),
              groupSearch.getStart(),
              groupSearch.getEnd(),
              groupSearch.getOrderByComparator());
    } else {
      long groupId =
          ParamUtil.getLong(portletRequest, "groupId", GroupConstants.DEFAULT_PARENT_GROUP_ID);

      int total =
          _groupLocalService.searchCount(
              company.getCompanyId(),
              _classNameIds,
              groupId,
              searchTerms.getKeywords(),
              getGroupParams(portletRequest, searchTerms, parentGroupId));

      groupSearch.setTotal(total);

      results =
          _groupLocalService.search(
              company.getCompanyId(),
              _classNameIds,
              groupId,
              searchTerms.getKeywords(),
              getGroupParams(portletRequest, searchTerms, parentGroupId),
              groupSearch.getStart(),
              groupSearch.getEnd(),
              groupSearch.getOrderByComparator());
    }

    groupSearch.setResults(results);

    return groupSearch;
  }
  public void setCompany(Company company) throws PortalException {
    _company = company;
    _companyGroupId = company.getGroupId();

    setAccount(company.getAccount());
  }