protected Group addScopeGroup() throws Exception {
    Group group = GroupTestUtil.addGroup();

    Layout layout = LayoutTestUtil.addLayout(group.getGroupId(), ServiceTestUtil.randomString());

    String name = ServiceTestUtil.randomString();

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

    Group scopeGroup =
        GroupLocalServiceUtil.addGroup(
            TestPropsValues.getUserId(),
            group.getParentGroupId(),
            Layout.class.getName(),
            layout.getPlid(),
            GroupConstants.DEFAULT_LIVE_GROUP_ID,
            name,
            ServiceTestUtil.randomString(),
            GroupConstants.TYPE_SITE_OPEN,
            true,
            GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
            StringPool.SLASH + FriendlyURLNormalizerUtil.normalize(name),
            false,
            true,
            serviceContext);

    return scopeGroup;
  }
  @Override
  public long getDDMTemplateGroupId(long groupId) {
    try {
      Group group = GroupLocalServiceUtil.getGroup(groupId);

      if (group.isLayout()) {
        group = group.getParentGroup();
      }

      if (group.isStagingGroup()) {
        Group liveGroup = group.getLiveGroup();

        if (!liveGroup.isStagedPortlet(PortletKeys.PORTLET_DISPLAY_TEMPLATE)) {

          return liveGroup.getGroupId();
        }
      }

      return group.getGroupId();
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }

    return groupId;
  }
  protected PortletDataContext createPortletDataContext(long companyId, long groupId) {

    PortletDataContext portletDataContext = new PortletDataContextImpl();

    try {
      Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(companyId);

      portletDataContext.setCompanyGroupId(companyGroup.getGroupId());
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }

    portletDataContext.setCompanyId(companyId);
    portletDataContext.setGroupId(groupId);
    portletDataContext.setScopeGroupId(groupId);

    try {
      Group userPersonalSiteGroup = GroupLocalServiceUtil.getUserPersonalSiteGroup(companyId);

      portletDataContext.setUserPersonalSiteGroupId(userPersonalSiteGroup.getGroupId());
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }

    return portletDataContext;
  }
  // TODO: allow for dynamic user url building classes to be injected
  private void addUsers(Element element, Group suppliedGroup, ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    // get all users
    List<User> users = UserLocalServiceUtil.getGroupUsers(suppliedGroup.getGroupId());

    // we're only displaying users with blogs for now
    for (User u : users) {
      Group usersOwnGroup =
          GroupLocalServiceUtil.getUserGroup(suppliedGroup.getCompanyId(), u.getUserId());

      int count = BlogsEntryLocalServiceUtil.getGroupEntriesCount(usersOwnGroup.getGroupId());
      List<BlogsEntry> entries =
          BlogsEntryLocalServiceUtil.getGroupEntries(usersOwnGroup.getGroupId(), 0, count);

      // only add if the user has blogs
      if (entries != null && entries.size() > 0) {

        // index the user, as well
        StringBuffer baseUrl = new StringBuffer(themeDisplay.getPortalURL());

        // TODO figure out where web comes from
        baseUrl.append("/web");
        baseUrl.append(usersOwnGroup.getFriendlyURL());

        Element userUrlElement = element.addElement("url");

        userUrlElement.addElement("loc").addText(encodeXML(baseUrl.toString()));
        userUrlElement.addElement("changefreq").addText("daily");
      }
    }
  }
  @Test
  public void testLocalizedSiteAddFileEntryType() throws Exception {
    Group group = GroupTestUtil.addGroup();

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

    Locale locale = LocaleThreadLocal.getSiteDefaultLocale();

    try {
      LocaleThreadLocal.setSiteDefaultLocale(LocaleUtil.SPAIN);

      String name = RandomTestUtil.randomString();
      String description = RandomTestUtil.randomString();
      DDMStructure ddmStructure =
          DDMStructureTestUtil.addStructure(
              DLFileEntry.class.getName(), new Locale[] {LocaleUtil.SPAIN}, LocaleUtil.SPAIN);

      DLFileEntryType dlFileEntryType =
          DLFileEntryTypeLocalServiceUtil.addFileEntryType(
              TestPropsValues.getUserId(),
              group.getGroupId(),
              name,
              description,
              new long[] {ddmStructure.getStructureId()},
              serviceContext);

      Assert.assertEquals(name, dlFileEntryType.getName(LocaleUtil.US, true));
      Assert.assertEquals(description, dlFileEntryType.getDescription(LocaleUtil.US, true));
    } finally {
      LocaleThreadLocal.setSiteDefaultLocale(locale);
    }
  }
  public static long getGroupId(long companyId, String[] pathArray) throws WebDAVException {

    try {
      if (pathArray.length == 0) {
        return 0;
      }

      String name = pathArray[0];

      Group group = GroupLocalServiceUtil.fetchFriendlyURLGroup(companyId, StringPool.SLASH + name);

      if (group != null) {
        return group.getGroupId();
      }

      User user = UserLocalServiceUtil.fetchUserByScreenName(companyId, name);

      if (user != null) {
        group = user.getGroup();

        return group.getGroupId();
      }
    } catch (Exception e) {
      throw new WebDAVException(e);
    }

    return 0;
  }
  @Override
  protected void validateImport(
      Map<String, List<StagedModel>> dependentStagedModelsMap, Group group) throws Exception {

    List<StagedModel> ddmStructureDependentStagedModels =
        dependentStagedModelsMap.get(DDMStructure.class.getSimpleName());

    Assert.assertEquals(1, ddmStructureDependentStagedModels.size());

    DDMStructure ddmStructure = (DDMStructure) ddmStructureDependentStagedModels.get(0);

    DDMStructureLocalServiceUtil.getDDMStructureByUuidAndGroupId(
        ddmStructure.getUuid(), group.getGroupId());

    List<StagedModel> dlFileEntryTypesDependentStagedModels =
        dependentStagedModelsMap.get(DLFileEntryType.class.getSimpleName());

    Assert.assertEquals(1, dlFileEntryTypesDependentStagedModels.size());

    DLFileEntryType dlFileEntryType =
        (DLFileEntryType) dlFileEntryTypesDependentStagedModels.get(0);

    DLFileEntryTypeLocalServiceUtil.getDLFileEntryTypeByUuidAndGroupId(
        dlFileEntryType.getUuid(), group.getGroupId());

    List<StagedModel> folderDependentStagedModels =
        dependentStagedModelsMap.get(DLFolder.class.getSimpleName());

    Assert.assertEquals(1, folderDependentStagedModels.size());

    Folder parentFolder = (Folder) folderDependentStagedModels.get(0);

    DLFolderLocalServiceUtil.getDLFolderByUuidAndGroupId(
        parentFolder.getUuid(), group.getGroupId());
  }
  protected Map<String, List<StagedModel>> addCompanyDependencies() throws Exception {

    Map<String, List<StagedModel>> dependentStagedModelsMap = new HashMap<>();

    Company company = CompanyLocalServiceUtil.fetchCompany(stagingGroup.getCompanyId());

    Group companyGroup = company.getGroup();

    DDMStructure ddmStructure =
        DDMStructureTestUtil.addStructure(
            companyGroup.getGroupId(), DLFileEntryType.class.getName());

    addDependentStagedModel(dependentStagedModelsMap, DDMStructure.class, ddmStructure);

    DLFileEntryType dlFileEntryType =
        DLAppTestUtil.addDLFileEntryType(companyGroup.getGroupId(), ddmStructure.getStructureId());

    addDependentStagedModel(dependentStagedModelsMap, DLFileEntryType.class, dlFileEntryType);

    Folder folder =
        DLAppTestUtil.addFolder(
            stagingGroup.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);

    addDependentStagedModel(dependentStagedModelsMap, DLFolder.class, folder);

    return dependentStagedModelsMap;
  }
  protected void trashFileEntry() throws Exception {
    Group group = ServiceTestUtil.addGroup();

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext();

    serviceContext.setScopeGroupId(group.getGroupId());

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

    int initialBaseModelsCount = getBaseModelsNotInTrashCount(parentBaseModel);
    int initialTrashEntriesCount = getTrashEntriesCount(group.getGroupId());

    BaseModel<?> baseModel = addBaseModel(parentBaseModel, true, serviceContext);

    DLFileShortcut dlFileShortcut = (DLFileShortcut) baseModel;

    FileEntry fileEntry = DLAppServiceUtil.getFileEntry(dlFileShortcut.getToFileEntryId());

    Assert.assertEquals(initialBaseModelsCount + 1, getBaseModelsNotInTrashCount(parentBaseModel));
    Assert.assertEquals(initialTrashEntriesCount, getTrashEntriesCount(group.getGroupId()));

    DLAppServiceUtil.moveFileEntryToTrash(fileEntry.getFileEntryId());

    Assert.assertEquals(initialBaseModelsCount, getBaseModelsNotInTrashCount(parentBaseModel));
    Assert.assertEquals(initialTrashEntriesCount + 1, getTrashEntriesCount(group.getGroupId()));

    DLAppServiceUtil.restoreFileEntryFromTrash(fileEntry.getFileEntryId());

    Assert.assertEquals(initialBaseModelsCount + 1, getBaseModelsNotInTrashCount(parentBaseModel));
  }
  protected void validateCompanyDependenciesImport(
      Map<String, List<StagedModel>> dependentStagedModelsMap, Group group) throws Exception {

    List<StagedModel> ddmStructureDependentStagedModels =
        dependentStagedModelsMap.get(DDMStructure.class.getSimpleName());

    Assert.assertEquals(1, ddmStructureDependentStagedModels.size());

    DDMStructure ddmStructure = (DDMStructure) ddmStructureDependentStagedModels.get(0);

    Assert.assertNull(
        "Company DDM structure dependency should not be imported",
        DDMStructureLocalServiceUtil.fetchDDMStructureByUuidAndGroupId(
            ddmStructure.getUuid(), group.getGroupId()));

    List<StagedModel> dlFileEntryTypesDependentStagedModels =
        dependentStagedModelsMap.get(DLFileEntryType.class.getSimpleName());

    Assert.assertEquals(1, dlFileEntryTypesDependentStagedModels.size());

    DLFileEntryType dlFileEntryType =
        (DLFileEntryType) dlFileEntryTypesDependentStagedModels.get(0);

    Assert.assertNull(
        "Company DL file entry should not be imported",
        DLFileEntryTypeLocalServiceUtil.fetchDLFileEntryTypeByUuidAndGroupId(
            dlFileEntryType.getUuid(), group.getGroupId()));
  }
  protected String fileUpload(
      CommandArgument commandArgument, String fileName, File file, String extension) {

    try {
      Group group = commandArgument.getCurrentGroup();

      Folder folder = _getFolder(group.getGroupId(), commandArgument.getCurrentFolder());

      long folderId = folder.getFolderId();
      String title = fileName;
      String description = StringPool.BLANK;
      String changeLog = StringPool.BLANK;

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(true);
      serviceContext.setAddGuestPermissions(true);

      DLAppServiceUtil.addFileEntry(
          group.getGroupId(), folderId, title, description, changeLog, file, serviceContext);
    } catch (Exception e) {
      throw new FCKException(e);
    }

    return "0";
  }
  @Test
  public void testFilterFindByG_N() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();

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

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

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

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

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

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

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

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

      Assert.assertEquals(StringUtil.toLowerCase(assetTagName), siteGroupAssetTag.getName());
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
    @Override
    public Void call() throws PortalException {
      Group group = _groupLocalService.getGroup(_groupId);

      Layout layout = _layoutLocalService.fetchLayout(_plid);

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

        if (layout != null) {
          layout =
              _layoutLocalService.fetchLayoutByUuidAndGroupId(
                  layout.getUuid(), group.getGroupId(), layout.isPrivateLayout());
        }
      }

      javax.portlet.PortletPreferences jxPortletPreferences = null;

      if (layout == null) {
        jxPortletPreferences =
            PortletPreferencesFactoryUtil.getStrictPortletSetup(
                group.getCompanyId(), group.getGroupId(), _portletId);
      } else {
        jxPortletPreferences =
            PortletPreferencesFactoryUtil.getStrictPortletSetup(layout, _portletId);
      }

      ExportImportDateUtil.updateLastPublishDate(
          _portletId, jxPortletPreferences, _dateRange, _endDate);

      return null;
    }
  public long getDDMTemplateGroupId(ThemeDisplay themeDisplay) {
    try {
      Group scopeGroup = themeDisplay.getScopeGroup();

      if (scopeGroup.isLayout()) {
        scopeGroup = scopeGroup.getParentGroup();
      }

      if (scopeGroup.isStagingGroup()) {
        Group liveGroup = scopeGroup.getLiveGroup();

        if (!liveGroup.isStagedPortlet(PortletKeys.PORTLET_DISPLAY_TEMPLATES)) {

          return liveGroup.getGroupId();
        }
      }

      return scopeGroup.getGroupId();
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }

    return themeDisplay.getScopeGroupId();
  }
  private void _getFolders(CommandArgument commandArgument, Document document, Node rootNode)
      throws Exception {

    Element foldersElement = document.createElement("Folders");

    rootNode.appendChild(foldersElement);

    if (commandArgument.getCurrentFolder().equals(StringPool.SLASH)) {
      getRootFolders(commandArgument, document, foldersElement);
    } else {
      Group group = commandArgument.getCurrentGroup();

      Folder folder = _getFolder(group.getGroupId(), commandArgument.getCurrentFolder());

      List<Folder> folders = DLAppServiceUtil.getFolders(group.getGroupId(), folder.getFolderId());

      for (Folder curFolder : folders) {
        Element folderElement = document.createElement("Folder");

        foldersElement.appendChild(folderElement);

        folderElement.setAttribute("name", curFolder.getName());
      }
    }
  }
  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()));
      }
    }
  }
  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>");
    }
  }
  protected long[] addRequiredGroups() throws Exception {
    Group requiredGroup1 = GroupTestUtil.addGroup();

    _requiredGroupIds[0] = requiredGroup1.getGroupId();

    Group requiredGroup2 = GroupTestUtil.addGroup();

    _requiredGroupIds[1] = requiredGroup2.getGroupId();

    return _requiredGroupIds;
  }
  protected long[] addStandardGroups() throws Exception {
    Group standardGroup1 = GroupTestUtil.addGroup();

    _standardGroupIds[0] = standardGroup1.getGroupId();

    Group standardGroup2 = GroupTestUtil.addGroup();

    _standardGroupIds[1] = standardGroup2.getGroupId();

    return _standardGroupIds;
  }
  protected long[] addForbiddenGroups() throws Exception {
    Group forbiddenGroup1 = GroupTestUtil.addGroup();

    _forbiddenGroupIds[0] = forbiddenGroup1.getGroupId();

    Group forbiddenGroup2 = GroupTestUtil.addGroup();

    _forbiddenGroupIds[1] = forbiddenGroup2.getGroupId();

    return _forbiddenGroupIds;
  }
  @Override
  public Layout getLayout() throws PortalException {
    Group group = getGroup();

    if (group.getPrivateLayoutsPageCount() > 0) {
      List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(group.getGroupId(), true);

      return layouts.get(0);
    }

    throw new NoSuchLayoutException("{groupId=" + group.getGroupId() + "}");
  }
  public static long[] getGroupIds(long groupId) throws PortalException, SystemException {

    Group scopeGroup = GroupLocalServiceUtil.getGroup(groupId);

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(scopeGroup.getCompanyId());

    if (scopeGroup.isLayout()) {
      return new long[] {scopeGroup.getParentGroupId(), companyGroup.getGroupId()};
    } else {
      return new long[] {groupId, companyGroup.getGroupId()};
    }
  }
  private void _getFolders(CommandArgument commandArgument, Document document, Node rootNode)
      throws Exception {

    Element foldersElement = document.createElement("Folders");

    rootNode.appendChild(foldersElement);

    if (commandArgument.getCurrentFolder().equals(StringPool.SLASH)) {
      getRootFolders(commandArgument, document, foldersElement);
    } else {
      Group group = commandArgument.getCurrentGroup();

      List<Layout> layouts = new ArrayList<Layout>();

      layouts.addAll(
          LayoutServiceUtil.getLayouts(
              group.getGroupId(), false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID));

      layouts.addAll(
          LayoutServiceUtil.getLayouts(
              group.getGroupId(), true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID));

      if (("/" + commandArgument.getCurrentGroupName() + "/")
          .equals(commandArgument.getCurrentFolder())) {

        for (Layout layout : layouts) {
          Element folderElement = document.createElement("Folder");

          foldersElement.appendChild(folderElement);

          folderElement.setAttribute("name", "~" + _getLayoutName(layout).replace('/', '>'));
        }
      } else {
        String layoutName = _getLayoutName(commandArgument.getCurrentFolder());

        Layout layout = _getLayout(group.getGroupId(), layoutName);

        if (layout != null) {
          List<Layout> layoutChildren = layout.getChildren();

          for (int i = 0; i < layoutChildren.size(); i++) {
            layout = layoutChildren.get(i);

            Element folderElement = document.createElement("Folder");

            foldersElement.appendChild(folderElement);

            folderElement.setAttribute("name", "~" + _getLayoutName(layout).replace('/', '>'));
          }
        }
      }
    }
  }
  @AccessControlled(guestAccessEnabled = true)
  @Override
  public List<SkinnyJournalArticle> getSkinnyJournalArticles(
      long companyId, String groupName, long ddmStructureId, String locale) throws Exception {

    List<SkinnyJournalArticle> skinnyJournalArticles = new ArrayList<>();

    Group group = groupLocalService.getGroup(companyId, groupName);

    DDMStructure ddmStructure = ddmStructureLocalService.getDDMStructure(ddmStructureId);

    Set<String> journalArticleIds = new HashSet<>();

    List<JournalArticle> journalArticles =
        journalArticleLocalService.getStructureArticles(
            group.getGroupId(), ddmStructure.getStructureKey());

    for (JournalArticle journalArticle : journalArticles) {
      if (journalArticleIds.contains(journalArticle.getArticleId())) {
        continue;
      }

      journalArticleIds.add(journalArticle.getArticleId());

      try {
        PermissionChecker permissionChecker = getPermissionChecker();

        if (permissionChecker.hasPermission(
            group.getGroupId(),
            JournalArticle.class.getName(),
            journalArticle.getResourcePrimKey(),
            ActionKeys.VIEW)) {

          JournalArticle latestJournalArticle =
              journalArticleLocalService.getLatestArticle(
                  group.getGroupId(),
                  journalArticle.getArticleId(),
                  WorkflowConstants.STATUS_APPROVED);

          SkinnyJournalArticle skinnyJournalArticle =
              getSkinnyJournalArticle(latestJournalArticle, locale);

          skinnyJournalArticles.add(skinnyJournalArticle);
        }
      } catch (NoSuchArticleException nsae) {
      }
    }

    return skinnyJournalArticles;
  }
  protected File[] exportLayouts(long userGroupId, Map<String, String[]> parameterMap)
      throws PortalException {

    File[] files = new File[2];

    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(userGroupId);

    User user = userLocalService.getUser(GetterUtil.getLong(PrincipalThreadLocal.getName()));

    Group group = userGroup.getGroup();

    if (userGroup.hasPrivateLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              true,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), true),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[0] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    if (userGroup.hasPublicLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              false,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), false),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[1] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    return files;
  }
  private static long _getGroupId(long companyId, String name) throws Exception {

    try {
      Group group = GroupLocalServiceUtil.getFriendlyURLGroup(companyId, StringPool.SLASH + name);

      return group.getGroupId();
    } catch (NoSuchGroupException nsge) {
    }

    User user = UserLocalServiceUtil.getUserByScreenName(companyId, name);

    Group group = user.getGroup();

    return group.getGroupId();
  }
  protected List<Layout> getCandidateLayouts(long plid, boolean privateLayout, KBArticle kbArticle)
      throws Exception {

    List<Layout> candidateLayouts = new ArrayList<>();

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

    if (group.isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(group.getClassPK());

      candidateLayouts.add(layout);

      group = layout.getGroup();
    }

    List<Layout> layouts =
        LayoutLocalServiceUtil.getLayouts(
            group.getGroupId(), privateLayout, LayoutConstants.TYPE_PORTLET);

    candidateLayouts.addAll(layouts);

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    if ((layout.getGroupId() == kbArticle.getGroupId()) && layout.isTypePortlet()) {

      candidateLayouts.remove(layout);
      candidateLayouts.add(0, layout);
    }

    return candidateLayouts;
  }
  public static Layout addLayout(
      Group group,
      boolean privateLayout,
      long parentLayoutId,
      String name,
      String friendlyURL,
      String layoutTemplateId)
      throws Exception {

    ServiceContext serviceContext = new ServiceContext();

    Layout layout =
        LayoutLocalServiceUtil.addLayout(
            group.getCreatorUserId(),
            group.getGroupId(),
            privateLayout,
            parentLayoutId,
            name,
            StringPool.BLANK,
            StringPool.BLANK,
            LayoutConstants.TYPE_PORTLET,
            false,
            friendlyURL,
            serviceContext);

    LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

    layoutTypePortlet.setLayoutTemplateId(0, layoutTemplateId, false);

    return LayoutLocalServiceUtil.updateLayout(
        layout.getGroupId(),
        layout.isPrivateLayout(),
        layout.getLayoutId(),
        layout.getTypeSettings());
  }
  @Override
  public String getURLViewInContext(
      LiferayPortletRequest liferayPortletRequest,
      LiferayPortletResponse liferayPortletResponse,
      String noSuchEntryRedirect)
      throws Exception {

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

    Layout layout = themeDisplay.getLayout();

    if (Validator.isNotNull(_article.getLayoutUuid())) {
      layout =
          LayoutLocalServiceUtil.getLayoutByUuidAndCompanyId(
              _article.getLayoutUuid(), _article.getCompanyId());
    }

    String portletId = (String) liferayPortletRequest.getAttribute(WebKeys.PORTLET_ID);

    PortletPreferences portletSetup =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

    String linkToLayoutUuid =
        GetterUtil.getString(portletSetup.getValue("portletSetupLinkToLayoutUuid", null));

    if (Validator.isNotNull(_article.getLayoutUuid()) && Validator.isNull(linkToLayoutUuid)) {

      Group group = themeDisplay.getScopeGroup();

      if (group.getGroupId() != _article.getGroupId()) {
        group = GroupLocalServiceUtil.getGroup(_article.getGroupId());
      }

      String groupFriendlyURL =
          PortalUtil.getGroupFriendlyURL(group, layout.isPrivateLayout(), themeDisplay);

      return PortalUtil.addPreservedParameters(
          themeDisplay,
          groupFriendlyURL
              .concat(JournalArticleConstants.CANONICAL_URL_SEPARATOR)
              .concat(_article.getUrlTitle()));
    }

    List<Long> hitLayoutIds =
        JournalContentSearchLocalServiceUtil.getLayoutIds(
            _article.getGroupId(), layout.isPrivateLayout(), _article.getArticleId());

    if (!hitLayoutIds.isEmpty()) {
      Long hitLayoutId = hitLayoutIds.get(0);

      Layout hitLayout =
          LayoutLocalServiceUtil.getLayout(
              _article.getGroupId(), layout.isPrivateLayout(), hitLayoutId.longValue());

      return PortalUtil.getLayoutURL(hitLayout, themeDisplay);
    }

    return noSuchEntryRedirect;
  }
  @Override
  protected void doUpgrade() throws Exception {
    List<User> users = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);

    for (User user : users) {
      try {
        if (user.isDefaultUser()) {
          continue;
        }

        Group group = user.getGroup();

        LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(group.getGroupId(), false);

        String themeId = layoutSet.getThemeId();

        if (!themeId.equals("so_WAR_sotheme")) {
          return;
        }

        Role role =
            RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SOCIAL_OFFICE_USER);

        UserLocalServiceUtil.addRoleUsers(role.getRoleId(), new long[] {user.getUserId()});

        updateUserGroup(group);
        updateSocialRelations(user);
      } catch (Exception e) {
      }
    }
  }