@Override
 public void persist() {
   if (this.isNew()) {
     KBArticleLocalServiceUtil.addKBArticle(this);
   } else {
     KBArticleLocalServiceUtil.updateKBArticle(this);
   }
 }
  protected void reindexKBArticles(long companyId) throws Exception {
    final ActionableDynamicQuery actionableDynamicQuery =
        KBArticleLocalServiceUtil.getActionableDynamicQuery();

    actionableDynamicQuery.setAddCriteriaMethod(
        new ActionableDynamicQuery.AddCriteriaMethod() {

          @Override
          public void addCriteria(DynamicQuery dynamicQuery) {
            Property property = PropertyFactoryUtil.forName("status");

            dynamicQuery.add(property.eq(WorkflowConstants.STATUS_APPROVED));
          }
        });
    actionableDynamicQuery.setCompanyId(companyId);
    actionableDynamicQuery.setPerformActionMethod(
        new ActionableDynamicQuery.PerformActionMethod() {

          @Override
          public void performAction(Object object) throws PortalException {

            KBArticle kbArticle = (KBArticle) object;

            Document document = getDocument(kbArticle);

            actionableDynamicQuery.addDocument(document);
          }
        });
    actionableDynamicQuery.setSearchEngineId(getSearchEngineId());

    actionableDynamicQuery.performActions();
  }
  @Override
  protected void doReindex(String className, long classPK) throws Exception {
    KBArticle kbArticle =
        KBArticleLocalServiceUtil.getLatestKBArticle(classPK, WorkflowConstants.STATUS_APPROVED);

    reindexKBArticles(kbArticle);
  }
  @Override
  public List<KBArticle> fetchStagedModelsByUuidAndCompanyId(String uuid, long companyId) {

    return KBArticleLocalServiceUtil.getKBArticlesByUuidAndCompanyId(
        uuid,
        companyId,
        QueryUtil.ALL_POS,
        QueryUtil.ALL_POS,
        new StagedModelModifiedDateComparator<KBArticle>());
  }
  public AssetRenderer getAssetRenderer(long classPK, int type)
      throws PortalException, SystemException {

    KBArticle kbArticle = null;

    if (type == TYPE_LATEST_APPROVED) {
      kbArticle =
          KBArticleLocalServiceUtil.getLatestKBArticle(classPK, WorkflowConstants.STATUS_APPROVED);

      return new KBArticleAssetRenderer(kbArticle);
    }

    try {
      kbArticle = KBArticleLocalServiceUtil.getKBArticle(classPK);
    } catch (NoSuchArticleException nsae) {
      kbArticle =
          KBArticleLocalServiceUtil.getLatestKBArticle(classPK, WorkflowConstants.STATUS_ANY);
    }

    return new KBArticleAssetRenderer(kbArticle);
  }
  protected void reindexKBArticles(long companyId) throws Exception {
    int count =
        KBArticleLocalServiceUtil.getCompanyKBArticlesCount(
            companyId, WorkflowConstants.STATUS_APPROVED);

    int pages = count / Indexer.DEFAULT_INTERVAL;

    for (int i = 0; i <= pages; i++) {
      int start = (i * Indexer.DEFAULT_INTERVAL);
      int end = start + Indexer.DEFAULT_INTERVAL;

      reindexKBArticles(companyId, start, end);
    }
  }
  protected void reindexKBArticles(KBArticle kbArticle) throws Exception {

    // See KBArticlePermission#contains

    List<KBArticle> kbArticles =
        KBArticleLocalServiceUtil.getKBArticleAndAllDescendants(
            kbArticle.getResourcePrimKey(), WorkflowConstants.STATUS_APPROVED, null);

    Collection<Document> documents = new ArrayList<Document>();

    for (KBArticle curKBArticle : kbArticles) {
      documents.add(getDocument(curKBArticle));
    }

    SearchEngineUtil.updateDocuments(kbArticle.getCompanyId(), documents);
  }
  protected KBArticle getKBArticle(long resourcePrimKey, int status) throws Exception {

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

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

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

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

      return null;
    }

    return kbArticle;
  }
  @Override
  public void render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {

    try {
      ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

      int status = getStatus(renderRequest);

      renderRequest.setAttribute(WebKeys.KNOWLEDGE_BASE_STATUS, status);

      KBArticle kbArticle = null;

      long resourcePrimKey = getResourcePrimKey(renderRequest);

      if (resourcePrimKey > 0) {
        kbArticle = KBArticleServiceUtil.getLatestKBArticle(resourcePrimKey, status);
      } else {
        List<KBArticle> kbArticles =
            KBArticleLocalServiceUtil.getGroupKBArticles(
                themeDisplay.getScopeGroupId(), status, 0, 1, new KBArticlePriorityComparator());

        if (!kbArticles.isEmpty()) {
          kbArticle = kbArticles.get(0);
        }
      }

      renderRequest.setAttribute(WebKeys.KNOWLEDGE_BASE_KB_ARTICLE, kbArticle);
    } catch (Exception e) {
      if (e instanceof NoSuchArticleException || e instanceof PrincipalException) {

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

        SessionMessages.add(
            renderRequest,
            PortalUtil.getPortletId(renderRequest)
                + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
      } else {
        throw new PortletException(e);
      }
    }

    super.render(renderRequest, renderResponse);
  }
  public void updateRootKBFolderId(ActionRequest actionRequest, ActionResponse actionResponse)
      throws PortalException {

    long kbFolderId = ParamUtil.getLong(actionRequest, "rootKBFolderId");

    if (kbFolderId == KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
      return;
    }

    KBFolder kbFolder = KBFolderServiceUtil.getKBFolder(kbFolderId);

    PortalPreferences portalPreferences =
        PortletPreferencesFactoryUtil.getPortalPreferences(
            PortalUtil.getLiferayPortletRequest(actionRequest));

    portalPreferences.setValue(
        PortletKeys.KNOWLEDGE_BASE_DISPLAY, "preferredKBFolderURLTitle", kbFolder.getUrlTitle());

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

    if (Validator.isNull(urlTitle)) {
      return;
    }

    KBArticle kbArticle =
        KBArticleLocalServiceUtil.fetchKBArticleByUrlTitle(
            kbFolder.getGroupId(), kbFolder.getUrlTitle(), urlTitle);

    if (kbArticle == null) {
      return;
    }

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

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

      return;
    }

    actionResponse.setRenderParameter("kbFolderUrlTitle", kbFolder.getUrlTitle());
    actionResponse.setRenderParameter("urlTitle", urlTitle);
  }
  protected void reindexKBArticles(long companyId, int start, int end) throws Exception {

    List<KBArticle> kbArticles =
        KBArticleLocalServiceUtil.getCompanyKBArticles(
            companyId,
            WorkflowConstants.STATUS_APPROVED,
            start,
            end,
            new KBArticleModifiedDateComparator());

    Collection<Document> documents = new ArrayList<Document>();

    for (KBArticle kbArticle : kbArticles) {
      Document document = getDocument(kbArticle);

      documents.add(document);
    }

    SearchEngineUtil.updateDocuments(companyId, documents);
  }
  protected void putTitle(JSONObject jsonObject, KBComment kbComment) {
    KBArticle kbArticle = null;
    KBTemplate kbTemplate = null;

    String className = kbComment.getClassName();

    try {
      if (className.equals(KBArticle.class.getName())) {
        kbArticle =
            KBArticleLocalServiceUtil.getLatestKBArticle(
                kbComment.getClassPK(), WorkflowConstants.STATUS_APPROVED);

        jsonObject.put("title", kbArticle.getTitle());
      } else if (className.equals(KBTemplate.class.getName())) {
        kbTemplate = KBTemplateLocalServiceUtil.getKBTemplate(kbComment.getClassPK());

        jsonObject.put("title", kbTemplate.getTitle());
      }
    } catch (Exception e) {
      _log.error(e);
    }
  }
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, KBArticle kbArticle)
      throws Exception {

    if (kbArticle.getParentResourcePrimKey() != KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      long kbArticleClassNameId = PortalUtil.getClassNameId(KBArticleConstants.getClassName());

      if (kbArticle.getParentResourceClassNameId() == kbArticleClassNameId) {

        KBArticle parentKBArticle =
            KBArticleLocalServiceUtil.getLatestKBArticle(
                kbArticle.getParentResourcePrimKey(), WorkflowConstants.STATUS_APPROVED);

        StagedModelDataHandlerUtil.exportReferenceStagedModel(
            portletDataContext,
            kbArticle,
            parentKBArticle,
            PortletDataContext.REFERENCE_TYPE_PARENT);
      } else {
        KBFolder parentKBFolder =
            KBFolderLocalServiceUtil.getKBFolder(kbArticle.getParentResourcePrimKey());

        StagedModelDataHandlerUtil.exportReferenceStagedModel(
            portletDataContext,
            kbArticle,
            parentKBFolder,
            PortletDataContext.REFERENCE_TYPE_PARENT);
      }
    }

    Element kbArticleElement = portletDataContext.getExportDataElement(kbArticle);

    exportKBArticleAttachments(portletDataContext, kbArticleElement, kbArticle);

    portletDataContext.addClassedModel(
        kbArticleElement, ExportImportPathUtil.getModelPath(kbArticle), kbArticle);
  }
  protected KBArticle addKBArticleMarkdown(
      long userId,
      long groupId,
      long parentResourcePrimaryKey,
      String markdown,
      String fileEntryName,
      ZipReader zipReader,
      Map<String, String> metadata,
      ServiceContext serviceContext)
      throws KBArticleImportException {

    if (Validator.isNull(markdown)) {
      throw new KBArticleImportException("Markdown is null for file entry " + fileEntryName);
    }

    KBArticleMarkdownConverter kbArticleMarkdownConverter =
        new KBArticleMarkdownConverter(markdown, fileEntryName, metadata);

    String urlTitle = kbArticleMarkdownConverter.getUrlTitle();

    KBArticle kbArticle = KBArticleLocalServiceUtil.fetchKBArticleByUrlTitle(groupId, urlTitle);

    try {
      if (kbArticle == null) {
        kbArticle =
            KBArticleLocalServiceUtil.addKBArticle(
                userId,
                parentResourcePrimaryKey,
                kbArticleMarkdownConverter.getTitle(),
                urlTitle,
                markdown,
                null,
                kbArticleMarkdownConverter.getSourceURL(),
                null,
                null,
                serviceContext);
      }
    } catch (Exception e) {
      StringBundler sb = new StringBundler(4);

      sb.append("Unable to add basic KB article for file entry ");
      sb.append(fileEntryName);
      sb.append(": ");
      sb.append(e.getLocalizedMessage());

      throw new KBArticleImportException(sb.toString(), e);
    }

    try {
      String html =
          kbArticleMarkdownConverter.processAttachmentsReferences(
              userId, kbArticle, zipReader, new HashMap<String, FileEntry>());

      return KBArticleLocalServiceUtil.updateKBArticle(
          userId,
          kbArticle.getResourcePrimKey(),
          kbArticleMarkdownConverter.getTitle(),
          html,
          kbArticle.getDescription(),
          kbArticleMarkdownConverter.getSourceURL(),
          null,
          null,
          null,
          serviceContext);
    } catch (Exception e) {
      StringBundler sb = new StringBundler(4);

      sb.append("Unable to update KB article for file entry ");
      sb.append(fileEntryName);
      sb.append(": ");
      sb.append(e.getLocalizedMessage());

      throw new KBArticleImportException(sb.toString(), e);
    }
  }
  protected PortletURL getKBArticleURL(
      long plid, boolean privateLayout, KBArticle kbArticle, HttpServletRequest request)
      throws Exception {

    PortletURL firstMatchPortletURL = null;

    List<Layout> layouts = getCandidateLayouts(plid, privateLayout, kbArticle);

    for (Layout layout : layouts) {
      LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

      List<Portlet> portlets = layoutTypePortlet.getAllPortlets();

      for (Portlet portlet : portlets) {
        String rootPortletId = PortletConstants.getRootPortletId(portlet.getPortletId());

        if (rootPortletId.equals(PortletKeys.KNOWLEDGE_BASE_DISPLAY)) {
          PortletPreferences portletPreferences =
              PortletPreferencesFactoryUtil.getPortletSetup(
                  layout, portlet.getPortletId(), StringPool.BLANK);

          long kbFolderClassNameId = PortalUtil.getClassNameId(KBFolderConstants.getClassName());

          long resourceClassNameId =
              GetterUtil.getLong(
                  portletPreferences.getValue("resourceClassNameId", null), kbFolderClassNameId);
          long resourcePrimKey =
              GetterUtil.getLong(
                  portletPreferences.getValue("resourcePrimKey", null),
                  KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);

          if (resourceClassNameId == kbFolderClassNameId) {
            if (isParentFolder(resourcePrimKey, kbArticle.getKbFolderId())) {

              return getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
            }
          } else if (resourcePrimKey == kbArticle.getResourcePrimKey()) {

            return getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
          }

          if (firstMatchPortletURL == null) {
            firstMatchPortletURL =
                getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
          }
        }

        if (rootPortletId.equals(PortletKeys.KNOWLEDGE_BASE_SECTION)) {
          PortletPreferences portletPreferences =
              PortletPreferencesFactoryUtil.getPortletSetup(
                  layout, portlet.getPortletId(), StringPool.BLANK);

          String[] kbArticlesSections =
              portletPreferences.getValues("kbArticlesSections", new String[0]);

          KBArticle rootKBArticle =
              KBArticleLocalServiceUtil.fetchLatestKBArticle(
                  kbArticle.getRootResourcePrimKey(), WorkflowConstants.STATUS_APPROVED);

          if (rootKBArticle == null) {
            continue;
          }

          String[] sections = AdminUtil.unescapeSections(rootKBArticle.getSections());

          for (String section : sections) {
            if (!ArrayUtil.contains(kbArticlesSections, section)) {
              continue;
            }

            return getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
          }
        }

        if (rootPortletId.equals(PortletKeys.KNOWLEDGE_BASE_ARTICLE)) {
          PortletPreferences portletPreferences =
              PortletPreferencesFactoryUtil.getPortletSetup(
                  layout, portlet.getPortletId(), StringPool.BLANK);

          long resourcePrimKey =
              GetterUtil.getLong(portletPreferences.getValue("resourcePrimKey", null));

          KBArticle selKBArticle =
              KBArticleLocalServiceUtil.fetchLatestKBArticle(
                  resourcePrimKey, WorkflowConstants.STATUS_APPROVED);

          if (selKBArticle == null) {
            continue;
          }

          long rootResourcePrimKey = kbArticle.getRootResourcePrimKey();
          long selRootResourcePrimKey = selKBArticle.getRootResourcePrimKey();

          if (rootResourcePrimKey == selRootResourcePrimKey) {
            return getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
          }

          if (firstMatchPortletURL == null) {
            firstMatchPortletURL =
                getKBArticleURL(layout.getPlid(), portlet.getPortletId(), kbArticle, request);
          }
        }
      }
    }

    return firstMatchPortletURL;
  }
  @Override
  public void render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {

    try {
      ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

      int status = getStatus(renderRequest);

      renderRequest.setAttribute(WebKeys.KNOWLEDGE_BASE_STATUS, status);

      KBArticle kbArticle = null;

      Tuple resourceTuple = getResourceTuple(renderRequest);

      long resourcePrimKey = (Long) resourceTuple.getObject(1);

      if (resourcePrimKey != KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
        long resourceClassNameId = (Long) resourceTuple.getObject(0);

        long kbFolderClassNameId = PortalUtil.getClassNameId(KBFolderConstants.getClassName());

        if (resourceClassNameId == kbFolderClassNameId) {
          PortalPreferences portalPreferences =
              PortletPreferencesFactoryUtil.getPortalPreferences(renderRequest);

          String preferredKBFolderURLTitle =
              portalPreferences.getValue(
                  PortletKeys.KNOWLEDGE_BASE_DISPLAY, "preferredKBFolderURLTitle");

          kbArticle =
              getKBFolderKBArticle(
                  themeDisplay.getScopeGroupId(), resourcePrimKey, preferredKBFolderURLTitle);
        } else {
          kbArticle = KBArticleServiceUtil.fetchLatestKBArticle(resourcePrimKey, status);
        }
      } else {
        long parentResourcePrimKey =
            ParamUtil.getLong(
                renderRequest, "parentResourcePrimKey", KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);

        if (parentResourcePrimKey == KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

          List<KBArticle> kbArticles =
              KBArticleLocalServiceUtil.getGroupKBArticles(
                  themeDisplay.getScopeGroupId(),
                  status,
                  0,
                  1,
                  new KBArticlePriorityComparator(true));

          if (!kbArticles.isEmpty()) {
            kbArticle = kbArticles.get(0);
          }
        }
      }

      renderRequest.setAttribute(WebKeys.KNOWLEDGE_BASE_KB_ARTICLE, kbArticle);
    } catch (Exception e) {
      if (e instanceof NoSuchArticleException || e instanceof PrincipalException) {

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

        SessionMessages.add(
            renderRequest,
            PortalUtil.getPortletId(renderRequest)
                + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
      } else {
        throw new PortletException(e);
      }
    }

    super.render(renderRequest, renderResponse);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, KBArticle kbArticle)
      throws Exception {

    long userId = portletDataContext.getUserId(kbArticle.getUserUuid());

    if (kbArticle.getParentResourcePrimKey() != KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      if (kbArticle.getClassNameId() == kbArticle.getParentResourceClassNameId()) {

        StagedModelDataHandlerUtil.importReferenceStagedModels(
            portletDataContext, kbArticle, KBArticle.class);
      } else {
        StagedModelDataHandlerUtil.importReferenceStagedModels(
            portletDataContext, kbArticle, KBFolder.class);
      }
    }

    Map<Long, Long> kbArticleResourcePrimKeys =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(KBArticle.class);

    long parentResourcePrimKey =
        MapUtil.getLong(
            kbArticleResourcePrimKeys,
            kbArticle.getParentResourcePrimKey(),
            KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);

    long resourcePrimaryKey =
        MapUtil.getLong(kbArticleResourcePrimKeys, kbArticle.getResourcePrimKey(), 0);

    if (parentResourcePrimKey == KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      Map<Long, Long> kbFolderResourcePrimKeys =
          (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(KBFolder.class);

      parentResourcePrimKey =
          MapUtil.getLong(
              kbFolderResourcePrimKeys,
              kbArticle.getParentResourcePrimKey(),
              KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
    }

    String[] sections = AdminUtil.unescapeSections(kbArticle.getSections());

    ServiceContext serviceContext = portletDataContext.createServiceContext(kbArticle);

    KBArticle importedKBArticle = null;

    if (portletDataContext.isDataStrategyMirror()) {
      KBArticle existingKBArticle =
          KBArticleUtil.fetchByR_V(resourcePrimaryKey, kbArticle.getVersion());

      if (existingKBArticle == null) {
        existingKBArticle =
            fetchStagedModelByUuidAndGroupId(
                kbArticle.getUuid(), portletDataContext.getScopeGroupId());
      }

      if (existingKBArticle == null) {
        serviceContext.setUuid(kbArticle.getUuid());

        existingKBArticle =
            KBArticleLocalServiceUtil.fetchLatestKBArticle(
                resourcePrimaryKey, WorkflowConstants.STATUS_ANY);

        if (existingKBArticle == null) {
          importedKBArticle =
              KBArticleLocalServiceUtil.addKBArticle(
                  userId,
                  kbArticle.getParentResourceClassNameId(),
                  parentResourcePrimKey,
                  kbArticle.getTitle(),
                  kbArticle.getUrlTitle(),
                  kbArticle.getContent(),
                  kbArticle.getDescription(),
                  kbArticle.getSourceURL(),
                  sections,
                  null,
                  serviceContext);

          KBArticleLocalServiceUtil.updatePriority(
              importedKBArticle.getResourcePrimKey(), kbArticle.getPriority());
        } else {
          KBArticleLocalServiceUtil.updateKBArticle(
              userId,
              existingKBArticle.getResourcePrimKey(),
              kbArticle.getTitle(),
              kbArticle.getContent(),
              kbArticle.getDescription(),
              kbArticle.getSourceURL(),
              sections,
              null,
              null,
              serviceContext);

          KBArticleLocalServiceUtil.moveKBArticle(
              userId,
              existingKBArticle.getResourcePrimKey(),
              existingKBArticle.getParentResourceClassNameId(),
              parentResourcePrimKey,
              kbArticle.getPriority());

          importedKBArticle =
              KBArticleLocalServiceUtil.getLatestKBArticle(
                  existingKBArticle.getResourcePrimKey(), WorkflowConstants.STATUS_APPROVED);
        }
      } else {
        importedKBArticle = existingKBArticle;
      }
    } else {
      importedKBArticle =
          KBArticleLocalServiceUtil.addKBArticle(
              userId,
              kbArticle.getParentResourceClassNameId(),
              parentResourcePrimKey,
              kbArticle.getTitle(),
              kbArticle.getUrlTitle(),
              kbArticle.getContent(),
              kbArticle.getDescription(),
              kbArticle.getSourceURL(),
              sections,
              null,
              serviceContext);

      KBArticleLocalServiceUtil.updatePriority(
          importedKBArticle.getResourcePrimKey(), kbArticle.getPriority());
    }

    importKBArticleAttachments(portletDataContext, kbArticle, importedKBArticle);

    portletDataContext.importClassedModel(kbArticle, importedKBArticle);

    if (!kbArticle.isMain()) {
      kbArticleResourcePrimKeys.put(
          kbArticle.getResourcePrimKey(), importedKBArticle.getResourcePrimKey());
    }
  }
 @Override
 public void deleteStagedModel(KBArticle kbArticle) throws PortalException {
   KBArticleLocalServiceUtil.deleteKBArticle(kbArticle);
 }
  @Override
  public KBArticle fetchStagedModelByUuidAndGroupId(String uuid, long groupId) {

    return KBArticleLocalServiceUtil.fetchKBArticleByUuidAndGroupId(uuid, groupId);
  }
  protected Tuple getResourceTuple(RenderRequest renderRequest) throws Exception {

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

    String urlTitle = ParamUtil.getString(renderRequest, "urlTitle");

    if (Validator.isNotNull(urlTitle)) {
      String kbFolderUrlTitle = ParamUtil.getString(renderRequest, "kbFolderUrlTitle");

      KBArticle kbArticle = null;

      if (Validator.isNotNull(kbFolderUrlTitle)) {
        kbArticle =
            KBArticleLocalServiceUtil.fetchKBArticleByUrlTitle(
                themeDisplay.getScopeGroupId(), kbFolderUrlTitle, urlTitle);
      } else {
        kbArticle =
            KBArticleLocalServiceUtil.fetchKBArticleByUrlTitle(
                themeDisplay.getScopeGroupId(),
                KBFolderConstants.DEFAULT_PARENT_FOLDER_ID,
                urlTitle);
      }

      if ((kbArticle != null)
          && KBArticlePermission.contains(
              themeDisplay.getPermissionChecker(), kbArticle, ActionKeys.VIEW)) {

        return new Tuple(kbArticle.getClassNameId(), kbArticle.getResourcePrimKey());
      }
    }

    PortletPreferences portletPreferences = renderRequest.getPreferences();

    long defaultResourcePrimKey =
        GetterUtil.getLong(portletPreferences.getValue("resourcePrimKey", null));

    String mvcPath = ParamUtil.getString(renderRequest, "mvcPath");

    if (((defaultResourcePrimKey == 0) && mvcPath.equals(viewTemplate))
        || mvcPath.equals("/display/select_configuration_article.jsp")) {

      return new Tuple(
          PortalUtil.getClassNameId(KBFolderConstants.getClassName()),
          KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
    }

    long defaultResourceClassNameId =
        GetterUtil.getLong(portletPreferences.getValue("resourceClassNameId", null));

    long resourceClassNameId =
        ParamUtil.getLong(renderRequest, "resourceClassNameId", defaultResourceClassNameId);

    long resourcePrimKey =
        ParamUtil.getLong(renderRequest, "resourcePrimKey", defaultResourcePrimKey);

    if ((resourcePrimKey == 0) || (resourcePrimKey != defaultResourcePrimKey)) {

      return new Tuple(resourceClassNameId, resourcePrimKey);
    }

    long kbFolderClassNameId = PortalUtil.getClassNameId(KBFolderConstants.getClassName());

    if (resourceClassNameId == kbFolderClassNameId) {
      KBFolder kbFolder = KBFolderLocalServiceUtil.fetchKBFolder(resourcePrimKey);

      if ((kbFolder != null)
          && !KBFolderPermission.contains(
              themeDisplay.getPermissionChecker(),
              themeDisplay.getScopeGroupId(),
              defaultResourcePrimKey,
              ActionKeys.VIEW)) {

        return new Tuple(
            PortalUtil.getClassNameId(KBFolderConstants.getClassName()),
            KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
      }
    } else {
      KBArticle kbArticle =
          KBArticleLocalServiceUtil.fetchLatestKBArticle(
              defaultResourcePrimKey, WorkflowConstants.STATUS_ANY);

      if ((kbArticle != null)
          && !KBArticlePermission.contains(
              themeDisplay.getPermissionChecker(), defaultResourcePrimKey, ActionKeys.VIEW)) {

        return new Tuple(
            PortalUtil.getClassNameId(KBFolderConstants.getClassName()),
            KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
      }
    }

    return new Tuple(defaultResourceClassNameId, defaultResourcePrimKey);
  }