package space.apps.moudules.website.services; import java.io.File; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import apps.pojo.Article; import apps.pojo.ArticleCopy; import apps.pojo.ArticleJumpTypeCode; import apps.pojo.Website; import apps.pojo.WebsiteNavigation; import space.apps.common.ConstVars.dataStatusCode; import space.apps.moudules.sys.utils.ChangeLogUtil; import space.apps.moudules.website.common.ConstVars.articleJumpTypeCode; import space.apps.moudules.website.common.ConstVars.articleStatusCode; import space.apps.moudules.website.template.util.WebsiteTemplateArticleUtil; import space.apps.moudules.website.template.util.WebsiteTemplateNavUtil; import space.apps.moudules.website.template.util.WebsiteUtil; import space.apps.moudules.website.util.AppWebsiteManageUtil; import space.core.apps.common.BaseTransaction; import space.core.apps.common.ConstVars; import space.core.apps.common.ScheduleImpl; import space.core.apps.common.bean.AppUser; import space.core.apps.common.bean.NextService; import space.core.apps.common.bean.ResponsePackage; import space.core.apps.util.GdbaQueryUtil; import space.core.apps.util.NextServiceUtil; import space.core.apps.util.WebEditorUtil; import space.core.common.utils.DateTimeUtil; import space.core.common.utils.FileUtil; import space.core.common.utils.GsonUtil; import space.core.common.utils.PojoUtil; import space.core.common.utils.StringUtil; import space.core.db.jdbc.GeneralDBAccess; import space.core.db.jdbc.SqlCommandImpl; /** * 文章服务类 * * @author SPACE * @date 2020年02月08日 */ public class ArticleService extends BaseTransaction { static Logger log = LogManager.getLogger(ArticleService.class); private static final long serialVersionUID = 1L; private static final String ARTICLE_PREVIEW_SESSION_PREFIX = "articlePreviewPath_"; private static final Long NAVIGATION_STYLE_GRAPHIC_LIST = 10010L; private static final String COLLEGE_RED_TEMPLATE_ID_CODE = "ffkjcollegered1"; private static final String ARTICLE_PUBLISHED_HISTORY_ROOT = "/web/upload/article-history/"; private static final String PUBLISHED_CONTENT_SNAPSHOT_FIELD = "publishedContentSnapshot"; private static final String PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD = "publishedEditContentSnapshot"; /** * 转换文章内容 html 里的链接 * * @param path * @param domain * @return * @throws Exception * @author 陈锋 * @log 2020年10月16日 */ private String converArticleContentHtmlLink(String path, String domain) throws Exception { File input = new File(path); Document doc = Jsoup.parse(input, "UTF-8", ""); replaceHtmlLink(doc, domain); imgSrcConverLazyloadSrc(doc); String html = doc.select("body").eq(0).html(); String articleTemplate = FileUtil.readFile( getWebRootPath() + space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_PATH); articleTemplate = articleTemplate .replace(space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_CONTENT_KEY, html); return articleTemplate; } /** * 替换 html 的链接 * * @param doc * @param domain * @author 陈锋 * @log 2020年10月16日 */ private void replaceHtmlLink(Document doc, String domain) { Elements srcEles = doc.select("[src]"); Elements hrefEles = doc.select("a[href]"); replaceAttrPrefix(srcEles, "src", domain); replaceAttrPrefix(hrefEles, "href", domain); } /** * 替换属性的前缀 * * @param attrEles 属性标签集合 * @param attr 属性名 * @param prefix 前缀 * @author 陈锋 * @log 2020年10月16日 */ private void replaceAttrPrefix(Elements attrEles, String attr, String prefix) { for (Element ele : attrEles) { String attrValue = ele.attr(attr); if (StringUtil.isNull(attrValue)) { continue; } if (shouldKeepOriginalAttrValue(attrValue)) { continue; } if (prefix.endsWith("/") && attrValue.startsWith("/")) { attrValue = prefix + attrValue.substring(1); } else { attrValue = prefix + attrValue; } ele.attr(attr, attrValue); } } private boolean shouldKeepOriginalAttrValue(String attrValue) { if (StringUtil.isNull(attrValue)) { return true; } String value = attrValue.trim().toLowerCase(); return value.startsWith("http://") || value.startsWith("https://") || value.startsWith("//") || value.startsWith("data:") || value.startsWith("blob:") || value.startsWith("mailto:") || value.startsWith("tel:") || value.startsWith("javascript:") || value.startsWith("#"); } /** * img 标签的 src 转为 jquery.lazyload.js 的懒加载的 data-original 属性 * * @param doc * @author 陈锋 * @log 2020年10月16日 */ private void imgSrcConverLazyloadSrc(Document doc) { Elements srcEles = doc.select("img[src]"); int i = 0; for (Element ele : srcEles) { i++; if (i <= 3) { continue; } String srcValue = ele.attr("src"); ele.removeAttr("src"); ele.attr("data-original", srcValue); } } /** * 保留手填摘要;未填写摘要时允许为空,不再从正文自动提取。 * * @param article 文章 * @param htmlContent html 正文内容 * @author 陈锋 * @log 2020年10月19日 */ private void saveArticleDesc(Article article, String htmlContent) { } /** * 文章录入 * * @return * @throws Exception * @author SPACE * @date 2020年02月09日 */ public String add() throws Exception { AppUser appUser = getAppUser(); GeneralDBAccess gdba = getGdbaInstance(); Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp(); String top = getParameter("top"); String timeSwitch = getParameter("timeSwitch"); String content = getParameterNotXSS("body"); Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class); String navIdList = getParameter("navIdList"); WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目"); if (wn == null) { return DEFAULT_FORWARD; } if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) { return DEFAULT_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) { return DEFAULT_FORWARD; } String editPath = WebEditorUtil.createHtmlFile(content); String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath, space.apps.moudules.website.common.ConstVars.domain); String runPath = WebEditorUtil.createHtmlFile(runContent); article.setContent(runPath);// 运行文件 article.setEditContent(editPath);// 编辑文件 article.setUnitid(appUser.getUnitId()); article.setDcode(dataStatusCode.INSERT.getCode()); article.setCreatePid(appUser.getUserId()); article.setLastChangePid(appUser.getUserId()); article.setCreateTime(nowTimestamp); // article.setReleaseTime(nowTimestamp); article.setLastChangeTime(nowTimestamp); article.setSticktop("yes".equals(top) ? 1L : 0L); article.setAscode(articleStatusCode.STAY_RELEASE.getCode());// 必填的 article.setWebsiteid(wn.getWebsiteid()); article.setRelease("yes".equals(timeSwitch) ? 1L : 0L); if (!article.getAjtcode().equals(10020L)) { article.setUrl(WebsiteTemplateArticleUtil.getArticleURL(wn)); } // if (StringUtil.isNull(article.getReleaseTime())) { // article.setReleaseTime(nowTimestamp); // } saveArticleDesc(article, content); gdba.insertByBean(article); saveArticleCopy(gdba, article, appUser, navIdList); initArticleSticktopSchedule(gdba, article, appUser); initArticleReleaseTaskSchedule(gdba, article, appUser); gdba.updateById(article); setArticleApplyService(article.getArticleid()); gdba.commit(); setResponsePackage(getResponseSuccessMsgPackage()); return DEFAULT_FORWARD; } /** * 设置文章申请服务 * * @param articleid 文章 id * @author 陈锋 * @log 2020年12月8日 下午8:28:18 */ private void setArticleApplyService(Long articleid) { // 设置下一个服务对象 if (isNextServiceFlag()) { Map paramsMap = NextServiceUtil.newHashMap(); paramsMap.put("articleid", articleid); NextService nextService = NextServiceUtil.getLayer("website.article_start", "sys.common_audit.apply", paramsMap); nextService.setRefresh(true); // 需要刷新 setNextService(nextService); } } /** * 文章修改 * * @return * @throws Exception * @author 陈锋 * @log 2020年9月18日 */ public String modify() throws Exception { GeneralDBAccess gdba = getGdbaInstance(); AppUser appUser = getAppUser(); Article a2 = new Article(); a2.setArticleid(getParameterToLong("articleid")); gdba.selectById(a2); if (!Long.valueOf(dataStatusCode.INSERT.getCode()).equals(a2.getDcode())) { // setResponsePackage(getResponseErrorMsgPackage()); StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("[").append(DateTimeUtil.getNowDate()).append("] - 文章修改,ip为:") .append(getRequest().getLocalAddr()).append(" 篡改的文章 id 为:").append(a2.getArticleid()) .append(",文章标题为:").append(a2.getTitle()); log.error(msgBuilder.toString()); return ERROR_FORWARD; } Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp(); String top = getParameter("top"); String timeSwitch = getParameter("timeSwitch"); String content = getParameterNotXSS("body"); String navIdList = getParameter("navIdList"); Article article = new Article(); article.setArticleid(a2.getArticleid()); gdba.selectById(article); PojoUtil.formatRequest(getRequest(), article); WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目"); if (wn == null) { return DEFAULT_FORWARD; } if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) { return DEFAULT_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) { return DEFAULT_FORWARD; } article.setSticktop("yes".equals(top) ? 1L : 0L); ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), GsonUtil.toJson(a2)); FileUtil.writeFile(content, getWebRootPath() + a2.getEditContent());// 编辑文件,获取页面上的正文内容 String runContent = converArticleContentHtmlLink(getWebRootPath() + a2.getEditContent(), space.apps.moudules.website.common.ConstVars.domain); FileUtil.writeFile(runContent, getWebRootPath() + a2.getContent());// 运行文件,从编辑文件里转换为运行文件 article.setLastChangePid(appUser.getUserId()); article.setLastChangeTime(nowTimestamp); article.setWebsiteid(wn.getWebsiteid()); article.setRelease("yes".equals(timeSwitch) ? 1L : 0L); // 旧的文章是定时发布的,新的文章不是定时发布的,则需要把发布时间设置为空 if (a2.getRelease().equals(1L) && !"yes".equals(timeSwitch)) { article.setReleaseTime(null); } verifyArticleUrl(article, a2, wn); saveArticleDesc(article, content); gdba.updateById(article); saveArticleCopy(gdba, article, appUser, navIdList); initArticleSticktopSchedule(gdba, article, appUser); initArticleReleaseTaskSchedule(gdba, article, appUser); gdba.updateById(article); setArticleApplyService(article.getArticleid()); gdba.commit(); setResponsePackage(getResponseSuccessMsgPackage()); return DEFAULT_FORWARD; } /** * 根据栏目 id 获取栏目对象 * * @param gdba * @param navigationId 栏目 id * @return * @throws Exception * @author 陈锋 * @log 2020年9月26日 */ private WebsiteNavigation getWebsiteNavigationById(GeneralDBAccess gdba, Long navigationId) throws Exception { WebsiteNavigation wn = new WebsiteNavigation(); wn.setNavigationid(navigationId); gdba.selectById(wn); return wn; } private WebsiteNavigation getArticleTargetNavigation(GeneralDBAccess gdba, Long navigationId, String targetName) throws Exception { if (navigationId == null || navigationId <= 0) { setResponsePackage(getResponseWarningMsgPackage("请选择" + targetName)); return null; } WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationId); if (!isArticleTargetNavigation(wn)) { setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择可发布文章的栏目")); return null; } if (hasEnabledChildNavigation(gdba, navigationId)) { setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择最下级栏目,请继续向右选择最后一级栏目")); return null; } return wn; } private boolean verifyArticleCopyNavigationList(GeneralDBAccess gdba, String navIdList, Article article) throws Exception { if (StringUtil.isNull(navIdList)) { return true; } Set navIdSet = new HashSet(); String[] navIdAry = navIdList.split(","); for (String navId : navIdAry) { if (StringUtil.isNull(navId) || navIdSet.contains(navId)) { continue; } navIdSet.add(navId); WebsiteNavigation wn = getArticleTargetNavigation(gdba, Long.valueOf(navId), "抄送栏目"); if (wn == null) { return false; } if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "抄送栏目")) { return false; } } return true; } private boolean verifyGraphicListThumbnailRequired(GeneralDBAccess gdba, WebsiteNavigation wn, Article article, String targetName) throws Exception { if (wn == null || !NAVIGATION_STYLE_GRAPHIC_LIST.equals(wn.getWnlscode())) { return true; } if (article != null && StringUtil.notNull(article.getThumbnail())) { return true; } setResponsePackage(getResponseWarningMsgPackage(targetName + "为图文列表时必须上传缩略图")); return false; } private boolean isCollegeRedGraphicListNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception { if (wn == null || !NAVIGATION_STYLE_GRAPHIC_LIST.equals(wn.getWnlscode())) { return false; } return isCollegeRedTemplateNavigation(gdba, wn); } private boolean isCollegeRedTemplateNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception { Long wtid = wn == null ? null : wn.getWtid(); if (wtid == null && wn != null && wn.getWebsiteid() != null) { Website website = WebsiteUtil.getWebsiteByID(gdba, wn.getWebsiteid()); wtid = website == null ? null : website.getWtid(); } if (wtid == null) { return false; } return isCollegeRedTemplateIdCode(gdba, wtid); } private boolean isCollegeRedTemplateIdCode(GeneralDBAccess gdba, Long wtid) throws Exception { String sql = " select id_code from website_template where wtid = :wtid "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("wtid", wtid); Map templateMap = gdba.selectAsMap(sqlCmd); Object idCode = templateMap == null ? null : templateMap.get("id_code"); return idCode != null && idCode.toString().indexOf(COLLEGE_RED_TEMPLATE_ID_CODE) >= 0; } private boolean isArticleTargetNavigation(WebsiteNavigation wn) { if (wn == null || wn.getWntcode() == null) { return false; } return isArticleTargetWntcode(wn.getWntcode()); } private boolean isArticleTargetWntcode(Object wntcode) { if (wntcode == null) { return false; } Long wntcodeLong = Long.valueOf(wntcode.toString()); return Long.valueOf(10010L).equals(wntcodeLong) || Long.valueOf(10060L).equals(wntcodeLong); } private boolean hasEnabledChildNavigation(GeneralDBAccess gdba, Long navigationId) throws Exception { String sql = " select count(*) as c from website_navigation where dcode = 61 and parent_nid = :navigationid "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("navigationid", navigationId); Map resultMap = gdba.selectAsMap(sqlCmd); return Integer.parseInt(resultMap.get("c").toString()) > 0; } /** * 验证文章的 url 是否需要生成新的、或使用旧的、或使用页面上的 * * @param newArticle 新文章对象(也就是更新的) * @param oldArticle 旧文章对象 * @param newArticleNavigation 新文章的的栏目对象 * @throws Exception * @author 陈锋 * @log 2020年10月11日 */ private void verifyArticleUrl(Article newArticle, Article oldArticle, WebsiteNavigation newArticleNavigation) throws Exception { // 新、旧都是一样 if (oldArticle.getAjtcode().equals(newArticle.getAjtcode())) { // 都是正文、无动作,则使用旧的 url if (!oldArticle.getAjtcode().equals(10020L)) {// 不是链接 newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url } // 都是链接时,则使用页面的,使用页面的不用重新设置 url } // 旧的是链接,新的不是链接时,则需要生成 url else if (oldArticle.getAjtcode().equals(10020L) && !newArticle.getAjtcode().equals(10020L)) { newArticle.setUrl(WebsiteTemplateArticleUtil.getArticleURL(newArticleNavigation));// 生成新的 url } // 新的为无动作,则使用旧的 else if (newArticle.getAjtcode().equals(10030L)) { newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url } // url 为空时,则用旧的 else if (newArticle.getUrl() == null) { newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url } } /** * 设置文章变动申请服务 * * @param articleid 文章 id * @author 陈锋 * @log 2020年12月8日 下午8:28:18 */ private void setArticleChangeApplyService(Long articleid) { // 设置下一个服务对象 if (isNextServiceFlag()) { Map paramsMap = NextServiceUtil.newHashMap(); paramsMap.put("articleid", articleid); NextService nextService = NextServiceUtil.getLayer("website.article_start_change", "sys.common_audit.change_apply", paramsMap); nextService.setRefresh(true); // 需要刷新 setNextService(nextService); } } /** * 文章变动 * * @return * @throws Exception * @author SPACE * @date 2020年02月09日 */ public String change() throws Exception { AppUser appUser = getAppUser(); GeneralDBAccess gdba = getGdbaInstance(); Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp(); String top = getParameter("top"); String timeSwitch = getParameter("timeSwitch"); String content = getParameterNotXSS("body"); String navIdList = getParameter("navIdList"); Article article = new Article(); article.setArticleid(getParameterToLong("articleid")); gdba.selectById(article); PojoUtil.formatRequest(getRequest(), article); WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目"); if (wn == null) { return TIPS_FORWARD; } if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) { return TIPS_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) { return TIPS_FORWARD; } article.setSticktop("yes".equals(top) ? 1L : 0L); Article a2 = new Article(); a2.setArticleid(article.getArticleid()); gdba.selectById(a2); ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), buildArticleChangeLogContent(a2, nowTimestamp)); verifyArticleUrl(article, a2, wn); FileUtil.writeFile(content, getWebRootPath() + a2.getEditContent());// 编辑文件,获取页面上的正文内容 String runContent = converArticleContentHtmlLink(getWebRootPath() + a2.getEditContent(), space.apps.moudules.website.common.ConstVars.domain); FileUtil.writeFile(runContent, getWebRootPath() + a2.getContent());// 运行文件,从编辑文件里转换为运行文件 article.setDcode(dataStatusCode.STAY_SUBMIT.getCode()); article.setLastChangePid(appUser.getUserId()); article.setLastChangeTime(nowTimestamp); article.setWebsiteid(wn.getWebsiteid()); article.setRelease("yes".equals(timeSwitch) ? 1L : 0L); // 旧的文章设置了定时发布、发布时间,为到指定的发布时间时 if (articleStatusCode.STAY_RELEASE.getCode().equals(a2.getAscode()) && a2.getRelease().equals(1L) && StringUtil.notNull(a2.getReleaseTaskSchedulesid())) { // 新的文章没有设置定时发布 if (article.getRelease().equals(0L)) { article.setReleaseTime(null); } } saveArticleDesc(article, content); saveArticleCopy(gdba, article, appUser, navIdList); initArticleSticktopSchedule(gdba, article, appUser); initArticleReleaseTaskSchedule(gdba, article, appUser); gdba.updateById(article); setArticleChangeApplyService(article.getArticleid()); gdba.commit(); setResponsePackage(getResponseSuccessMsgPackage()); return TIPS_FORWARD; } private String buildArticleChangeLogContent(Article article, Timestamp snapshotTime) throws Exception { JsonObject logContent = new JsonParser().parse(GsonUtil.toJson(article)).getAsJsonObject(); if (!isPublishedArticle(article)) { return logContent.toString(); } String contentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getContent(), "content", snapshotTime); if (StringUtil.notNull(contentSnapshot)) { logContent.addProperty(PUBLISHED_CONTENT_SNAPSHOT_FIELD, contentSnapshot); } String editContentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getEditContent(), "edit-content", snapshotTime); if (StringUtil.notNull(editContentSnapshot)) { logContent.addProperty(PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD, editContentSnapshot); } return logContent.toString(); } private boolean isPublishedArticle(Article article) { return Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode()) && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode()); } private String copyPublishedArticleFile(Long articleid, String filePath, String fileType, Timestamp snapshotTime) throws Exception { if (StringUtil.isNull(filePath)) { return null; } File source = new File(getWebRootPath() + filePath); if (!source.exists() || !source.isFile()) { return null; } String snapshotDir = ARTICLE_PUBLISHED_HISTORY_ROOT + articleid + "/"; FileUtil.makeDirectory(new File(getWebRootPath() + snapshotDir)); String fileExt = FileUtil.getFileExt(filePath); if (StringUtil.isNull(fileExt)) { fileExt = "html"; } else if (fileExt.startsWith(".")) { fileExt = fileExt.substring(1); } String snapshotPath = snapshotDir + DateTimeUtil.formatDate(snapshotTime, "yyyyMMddHHmmssSSS") + "-" + fileType + "." + fileExt; FileUtil.copyFile(source.getAbsolutePath(), getWebRootPath() + snapshotPath); return snapshotPath; } /** * 删除指定文章的所有抄送记录 * * @param gdba * @param article * @throws Exception * @author SPACE * @date 2020年02月09日 */ private void delArticleCopy(GeneralDBAccess gdba, Article article) throws Exception { String sql = " delete from article_copy where articleid = :articleid "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("articleid", article.getArticleid()); gdba.modify(sqlCmd); } /** * 查询指定文章所抄送的栏目列表 * * @param gdba * @param article * @return * @throws Exception * @author SPACE * @date 2020年02月09日 */ private List> getArticleCopyList(GeneralDBAccess gdba, Article article) throws Exception { String sql = " SELECT wn.navigationid, wn.name, wn.parent_nid, ac.dcode FROM article_copy ac, website_navigation wn where ac.navigationid =" + " wn.navigationid and ac.articleid = :articleid "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("articleid", article.getArticleid()); return gdba.selectAsMapList(sqlCmd); } /** * 获取可以抄送的栏目 * * @throws Exception * @author SPACE * @date 2020年02月09日 */ public void getCopyNavigation() throws Exception { GeneralDBAccess gdba = getGdbaInstance(); AppUser appUser = getAppUser(); List> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser, 10010L); ResponsePackage rp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList)); write(rp.toJsonWriteNonStringValueAsString()); // getWriter().write(FastjsonUtil.toStringJSON(getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList)))); } /** * 获取可以发布的栏目 * * @throws Exception * @author SPACE * @date 2020年02月08日 */ public void getIssueNavigation() throws Exception { GeneralDBAccess gdba = getGdbaInstance(); AppUser appUser = getAppUser(); List> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser, 10000L); ResponsePackage rsdp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList)); write(rsdp.toJsonWriteNonStringValueAsString()); } /** * 将栏目的名称修改为:上级栏目链/栏目名称 * * @param gdba * @param navigationList * @throws Exception * @author SPACE * @date 2020年02月27日 */ void getNavAllParentName(GeneralDBAccess gdba, List> navigationList) throws Exception { for (Map map : navigationList) { Object parNid = map.get("parent_nid"); if (StringUtil.isNull(parNid)) { continue; } map.put("name", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString()))); } } /** * 根据栏目ID获取栏目上级链名称 * * @param gdba 数据库 * @param navID 栏目ID * @throws Exception * @author SPACE * @date 2020年02月27日 */ String getNavAllParentName(GeneralDBAccess gdba, Long navID) throws Exception { List navParentList = WebsiteTemplateNavUtil.getNavParentList(gdba, navID); if (navParentList.size() == 1) { return navParentList.get(0).getName(); } StringBuilder nameBuilder = new StringBuilder(); for (WebsiteNavigation wn : navParentList) { nameBuilder.append(wn.getName()).append(" / "); } return nameBuilder.substring(0, nameBuilder.length() - 2); } Map getNavigationMap(GeneralDBAccess gdba, List> navigationList) throws Exception { Map retMap = new HashMap(); if (navigationList == null || navigationList.size() == 0) { retMap.put("data", new ArrayList>()); return retMap; } Set websiteSet = new HashSet(); Map>> websiteNavigationMap = new LinkedHashMap>>(); for (Map map : navigationList) { String website = map.get("websiteid").toString(); websiteSet.add(website); List> websiteNavigationList = websiteNavigationMap.get(website); if (websiteNavigationList == null) { websiteNavigationList = new ArrayList>(); websiteNavigationMap.put(website, websiteNavigationList); } websiteNavigationList.add(map); } if (websiteSet.size() > 1) { List> dataList = new ArrayList>(); for (String websiteId : websiteNavigationMap.keySet()) { Website w = new Website(); w.setWebsiteid(Long.valueOf(websiteId)); gdba.selectById(w); Map map = new HashMap(); map.put("navigationid", "-1"); map.put("name", w.getName()); map.put("children", buildNavigationTree(websiteNavigationMap.get(websiteId))); dataList.add(map); } retMap.put("data", dataList); } else { retMap.put("data", buildNavigationTree(navigationList)); } return retMap; } List> buildNavigationTree(List> navigationList) { Map> navigationMap = new LinkedHashMap>(); for (Map navigation : navigationList) { Map item = new HashMap(navigation); item.remove("children"); navigationMap.put(item.get("navigationid").toString(), item); } List> rootList = new ArrayList>(); for (Map navigation : navigationMap.values()) { Object parentNid = navigation.get("parent_nid"); Map parent = parentNid == null ? null : navigationMap.get(parentNid.toString()); if (parent == null) { rootList.add(navigation); continue; } @SuppressWarnings("unchecked") List> children = (List>) parent.get("children"); if (children == null) { children = new ArrayList>(); parent.put("children", children); } children.add(navigation); } setDisabledNavigationList(rootList); return rootList; } private void setDisabledNavigationList(List> navigationList) { for (Map navigation : navigationList) { @SuppressWarnings("unchecked") List> children = (List>) navigation.get("children"); if (children != null && children.size() > 0) { setDisabledNavigationList(children); continue; } if (!isArticleTargetWntcode(navigation.get("wntcode"))) { navigation.put("disabled", true); } } } /** * 文章信息 * * @return * @throws Exception * @author SPACE * @date 2020年02月09日 */ public String info() throws Exception { Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class); GeneralDBAccess gdba = getGdbaInstance(); gdba.selectById(article); List> articleCopyList = getArticleCopyList(gdba, article); getNavAllParentName(gdba, articleCopyList); String navAllName = getNavAllParentName(gdba, article.getNavigationid()); Website website = new Website(); website.setWebsiteid(article.getWebsiteid()); gdba.selectById(website); if (!articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode()) || (articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode()) && article.getUrl().startsWith("/"))) { // 设置查看文章时的 url String url = appendWebsiteDomain(website.getPort().toString(), website.getDomains(), website.getProtocol(), article.getUrl()); article.setUrl(url); } boolean isShowModifyReleaseTime = false;// 是否显示修改发布时间,默认不显示 // 变动时的发布时间,在用状态、已发布 if (Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode()) && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) { isShowModifyReleaseTime = true; } // 修改时的发布时间,录入状态、待发布、不是定时发布 if (Long.valueOf(dataStatusCode.INSERT.getCode()).equals(article.getDcode()) && article.getRelease() == 0L) { isShowModifyReleaseTime = true; } boolean isShowpreview = false;// 是否显示预览,默认不显示 // 文章数据状态为 在用,文章状态 已发布 if (article.getDcode().equals(Long.valueOf(dataStatusCode.USE.getCode())) && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) { // 文章动作 跳转正文页 或 自定义链接 if (article.getAjtcode().equals(articleJumpTypeCode.MAIN_BODY.getCode()) || article.getAjtcode().equals(articleJumpTypeCode.CUSTOM_LINK.getCode())) { isShowpreview = true; } } setRequestAttribute("isShowpreview", isShowpreview);// 是否显示预览 setRequestAttribute("isShowModifyReleaseTime", isShowModifyReleaseTime);// 是否显示修改发布时间 setRequestAttribute("article", article); setRequestAttribute("navAllName", navAllName); setRequestAttribute("copyNav", GsonUtil.toJson(articleCopyList)); try { setRequestAttribute("body", FileUtil.readFile(getWebRootPath() + article.getContent())); } catch (Exception e) { setRequestAttribute("body", "内容文件不存在或已被删除"); } try { setRequestAttribute("editBody", FileUtil.readFile(getWebRootPath() + article.getEditContent())); } catch (Exception e) { setRequestAttribute("editBody", "内容文件不存在或已被删除"); } ArticleJumpTypeCode ajtCode = new ArticleJumpTypeCode(); ajtCode.setAjtcode(article.getAjtcode()); gdba.selectById(ajtCode); setRequestAttribute("ajtCode", ajtCode);// 查看文章时用到 return DEFAULT_FORWARD; } /** * 拼接网站域名 * * @param port 端口 * @param domains 域名 * @param protocol 协议 * @param catalogURI 目录 * @return 带有协议和端口的网站域名 * @author SPACE * @log Oct 9, 2020 11:16:33 PM */ private static String appendWebsiteDomain(String port, String domains, String protocol, String catalogURI) { String href = null; String[] domainsAry = domains.split(";"); if (domainsAry.length > 0) { port = "80".equals(port) ? "" : (":" + port); // 非 80 端口进行特殊处理 if (domainsAry[0].endsWith("/")) { domainsAry[0] = domainsAry[0].substring(0, domainsAry[0].lastIndexOf("/")); } href = protocol + "://" + domainsAry[0] + port + catalogURI; } // 未找到域名 else { href = "javascript:alert('website domain is null!');"; } return href; } /** * 文章置顶周期 * * @param article * @throws Exception * @author SPACE * @date 2020年02月09日 */ private void initArticleSticktopSchedule(GeneralDBAccess gdba, Article article, AppUser appUser) throws ParseException, Exception { // 删除掉已经添加了的定时任务 if (StringUtil.notNull(article.getSticktopSchedulesid())) { ScheduleImpl.delSchedule(article.getSticktopSchedulesid(), gdba); } // 不置顶 if (article.getSticktop() == 0) { article.setSticktopEndTime(null); return; } // 非在用状态 if (!article.getDcode().equals(61L)) { return; } Map data = new HashMap(); data.put("articleid", article.getArticleid()); Long scheduleid = ScheduleImpl.addSchedule( "文章“" + article.getArticleid() + "/" + article.getTitle() + "”置顶周期任务", DateTimeUtil.formatDateYMdHms(article.getSticktopEndTime()), "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleSticktop", appUser.getUserId(), data, gdba); article.setSticktopSchedulesid(scheduleid); } /** * 文章定时发布任务 * * @param gdba * @param article * @param appUser * @throws Exception * @author 陈锋 * @log 2020年9月16日 */ private void initArticleReleaseTaskSchedule(GeneralDBAccess gdba, Article article, AppUser appUser) throws Exception { // 删掉已经添加的定时发布文章任务 if (StringUtil.notNull(article.getReleaseTaskSchedulesid())) { ScheduleImpl.delSchedule(article.getReleaseTaskSchedulesid(), gdba); article.setReleaseTaskSchedulesid(null); } if (article.getRelease() == 0) { // article.setReleaseTime(null); return; } article.setAscode(articleStatusCode.STAY_RELEASE.getCode()); Map data = new HashMap(); data.put("articleid", article.getArticleid()); Long scheduleid = ScheduleImpl.addSchedule( "文章“" + article.getArticleid() + "/" + article.getTitle() + "”定时发布任务", DateTimeUtil.formatDateYMdHms(article.getReleaseTime()), "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleRelease", appUser.getUserId(), data, gdba); article.setReleaseTaskSchedulesid(scheduleid); } /** * 文章列表 * * @return * @throws Exception * @author SPACE * @date 2020年02月09日 */ public String list() throws Exception { AppUser appUser = getAppUser(); StringBuilder sqlBuilder = new StringBuilder(" Select "); sqlBuilder.append( " a.articleid, a.dcode, a.thumbnail, (Select name from data_status_code dsc where dsc.dcode = a.dcode) as 'dsname', a.ascode, a" + ".websiteid, a.title, a.navigationid, a.ajtcode, a.sticktop, a.release_time, a.read_count, a.create_pid, date_format(a" + ".create_time, '%Y-%m-%d') as 'ctime', concat(per.name, ' / ', dep.name) pname_dname "); sqlBuilder.append( " ,(Select name from website_navigation wn where wn.navigationid = a.navigationid ) as 'navname'"); sqlBuilder.append( " ,(Select name from website w where w.websiteid = a.websiteid ) as 'website_name', dep.departmentid "); sqlBuilder.append(" from article a "); sqlBuilder.append(" left join person per on a.create_pid = per.personid "); sqlBuilder.append(" left join department dep on per.departmentid = dep.departmentid "); sqlBuilder.append( " where a.unitid = :unitid and if((a.dcode in (11, 21)), (a.create_pid = :createPid), (a.create_pid > 0)) "); sqlBuilder.append(" and a.dcode != 72 "); // 过滤已删除的数据 SqlCommandImpl sqlCmd = new SqlCommandImpl(); sqlCmd.setString("unitid", appUser.getUnitId()).setString("createPid", appUser.getUserId()); GdbaQueryUtil.appendLikeSql(sqlBuilder, sqlCmd, "title", getParameter("title")); // 标题 GdbaQueryUtil.appendFieldSql(sqlBuilder, sqlCmd, "a.dcode", getParameter("dcode")); // 数据状态码 // 栏目 String navigation = getParameter("navigation"); if (StringUtil.notNull(navigation)) { sqlBuilder.append("and (" + GdbaQueryUtil.getInSql(sqlCmd, "navigationid", navigation, ",") + "or articleid in (Select ac.articleid from website_navigation wn, article_copy ac, article a " + "where wn.navigationid = ac.navigationid and a.articleid = ac.articleid and ac.dcode = 61 and a.dcode = 61 " + "and wn.dcode = 61 and " + GdbaQueryUtil.getInSql(sqlCmd, "ac.navigationid", navigation, ",") + " ))"); } // 我发布的 String issue = getParameter("issue"); if (StringUtil.notNull(issue) && ConstVars.TRUE.equals(issue)) { sqlBuilder.append(" and a.create_pid = :cpid "); sqlCmd.setString("cpid", appUser.getUserId()); } /* 年月日 */ String dateTime = getParameter("dateTime"); if (StringUtil.notNull(dateTime)) { String[] dateTimeAry = dateTime.split(","); sqlBuilder.append( " and date_format(release_time, '%Y-%m-%d') >= date_format(:startTime, '%Y-%m-%d') and date_format(release_time, '%Y-%m-%d') <=" + " date_format(:endTime, '%Y-%m-%d') "); sqlCmd.setString("startTime", dateTimeAry[0]).setString("endTime", dateTimeAry[1]); } GeneralDBAccess gdba = getGdbaInstance(); // 获取可管理的网站 List> manageWebsiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(gdba, getAppUser()); if (manageWebsiteList.size() > 0) { sqlBuilder.append(" and ( ").append(GdbaQueryUtil.getInSql(sqlCmd, "a.websiteid", AppWebsiteManageUtil.websiteListIDToAry(manageWebsiteList))); sqlBuilder.append("or (a.create_pid = :cpid2 )) "); } else { sqlBuilder.append(" and (a.create_pid = :cpid2 ) "); } sqlCmd.setString("cpid2", appUser.getUserId()); // 排序方式 String sort = getParameter("sort"); if (StringUtil.isNull(sort) || "sort_new".equals(sort)) { sqlBuilder.append(" order by dcode asc, sticktop desc, release_time desc, articleid asc "); } else if ("sort_top".equals(sort)) { sqlBuilder.append(" order by dcode asc, read_count desc, articleid asc "); } else if ("sort_bottom".equals(sort)) { sqlBuilder.append(" order by dcode asc, read_count asc, articleid asc "); } sqlCmd.setExecuteSql(sqlBuilder.toString()); List> articleList = gdba.selectAsMapList(sqlCmd, getAppsPageBean()); for (Map map : articleList) { // 校验是否拥有该网站的管理权限 for (Map websiteMap : manageWebsiteList) { if (map.get("websiteid").toString().equals(websiteMap.get("websiteid").toString())) { map.put("isManagerDepartmentArticleFlag", "true"); break; } } map.put("navAllName", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString()))); } ResponsePackage rsp = getResponseSuccessPackage(); rsp.setRequestAttribute("articleList", articleList); setResponsePackage(rsp); return DEFAULT_FORWARD; } /** * 保存文章抄送 * * @param gdba * @param article * @param appUser * @param navIdList * @throws Exception * @author SPACE * @date 2020年02月09日 */ private void saveArticleCopy(GeneralDBAccess gdba, Article article, AppUser appUser, String navIdList) throws Exception { delArticleCopy(gdba, article); if (StringUtil.isNull(navIdList)) { return; } Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp(); String[] navIdAry = navIdList.split(","); Set navIdSet = new HashSet(); for (String navId : navIdAry) { if (navIdSet.contains(navId)) { continue; } navIdSet.add(navId); ArticleCopy ac = new ArticleCopy(); ac.setArticleid(article.getArticleid()); ac.setNavigationid(Long.valueOf(navId)); ac.setCreatePid(appUser.getUserId()); ac.setCreateTime(nowTimestamp); ac.setDcode(dataStatusCode.INSERT_AUDIT.getCode()); gdba.insertByBean(ac); } } /** * 文章录入前置服务 * * @return * @throws Exception * @author SPACE * @log Oct 14, 2020 10:32:06 PM */ public String articleAddBefore() throws Exception { List> websiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(getGdbaInstance(), getAppUser()); // 默认找可管理的第一个网站 if (websiteList != null && websiteList.size() > 0) { setRequestAttribute("article_sources", websiteList.get(0).get("name")); } return DEFAULT_FORWARD; } /** * 生成文章正文临时预览。 * * @throws Exception * @author SPACE */ public void preview() throws Exception { String content = getParameterNotXSS("body"); Long navigationid = getParameterToLong("navigationid"); if (StringUtil.isNull(content)) { write(getResponseWarningMsgPackage("正文内容为空").toJson()); return; } if (navigationid == null || navigationid <= 0) { write(getResponseWarningMsgPackage("请先选择发布栏目").toJson()); return; } GeneralDBAccess gdba = getGdbaInstance(); WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationid); if (!isArticleTargetNavigation(wn)) { write(getResponseWarningMsgPackage("发布栏目必须选择可发布文章的栏目").toJson()); return; } if (hasEnabledChildNavigation(gdba, navigationid)) { write(getResponseWarningMsgPackage("发布栏目必须选择最下级栏目,请继续向右选择最后一级栏目").toJson()); return; } String editPath = WebEditorUtil.createHtmlFile(content); String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath, space.apps.moudules.website.common.ConstVars.domain); String runPath = WebEditorUtil.createHtmlFile(runContent); String previewKey = java.util.UUID.randomUUID().toString().replace("-", ""); setSessionAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + previewKey, runPath); Map retMap = new HashMap(); retMap.put("url", "/apps?ark=website.article_preview_view&key=" + URLEncoder.encode(previewKey, "UTF-8")); write(getResponseSuccessDataPackage(retMap).toJsonWriteNonStringValueAsString()); } /** * 输出文章正文临时预览内容。 * * @throws Exception * @author SPACE */ public void previewView() throws Exception { getResponse().setContentType("text/html;charset=UTF-8"); String key = getParameter("key"); if (StringUtil.isNull(key)) { writePreviewUnavailable(); return; } Object previewPathObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key); String previewPath = previewPathObj == null ? "" : previewPathObj.toString(); File previewFile = getSafePreviewFile(previewPath); if (previewFile == null) { writePreviewUnavailable(); return; } write(FileUtil.readFile(previewFile.getPath())); } private File getSafePreviewFile(String previewPath) throws Exception { if (StringUtil.isNull(previewPath)) { return null; } String normalizedPath = previewPath.replace("\\", "/"); if (!normalizedPath.endsWith(".html")) { return null; } File webRoot = new File(getWebRootPath()).getCanonicalFile(); File uploadRoot = new File(webRoot, "web/upload").getCanonicalFile(); File previewFile = normalizedPath.startsWith("/") ? new File(webRoot, normalizedPath.substring(1)).getCanonicalFile() : new File(webRoot, normalizedPath).getCanonicalFile(); if (!previewFile.getPath().startsWith(uploadRoot.getPath() + File.separator)) { return null; } return previewFile.isFile() ? previewFile : null; } private void writePreviewUnavailable() throws Exception { write("
预览内容不存在,请刷新预览后再查看。
"); } // 测试的服务 /** * 重置文章运行文件,主要是替换链接的域名,固定替换为 space.apps.moudules.website.common.ConstVars.domain * * @return * @throws Exception * @author 陈锋 * @log 2020年10月19日 */ public String resetArticleRunHtmlLink() throws Exception { GeneralDBAccess gdba = getGdbaInstance(); SqlCommandImpl sqlCmd = new SqlCommandImpl("select * from article "); @SuppressWarnings("unchecked") List
articleList = gdba.selectAsList(sqlCmd, Article.class); String webPath = getWebRootPath(); for (Article article : articleList) { File file = new File(webPath + article.getContent()); if (".DS_Store".equals(file.getName())) { continue; } if (!file.isFile()) { continue; } String content = converArticleContentHtmlLink(file, space.apps.moudules.website.common.ConstVars.domain, webPath); FileUtil.writeFile(content, file.getPath()); } ResponsePackage rp = getResponseSuccessPackage(); setResponsePackage(rp); return DEFAULT_FORWARD; } /** * 转换文章内容 html 里的链接 * * @param path * @param domain * @return * @throws Exception * @author 陈锋 * @log 2020年10月16日 */ private String converArticleContentHtmlLink(File input, String domain, String webPath) throws Exception { Document doc = Jsoup.parse(input, "UTF-8", ""); Elements srcEles = doc.select("img[src]"); Elements originalEles = doc.select("img[data-original]"); Elements hrefEles = doc.select("a[href]"); replaceAllHtmlLink(srcEles, "src", domain); replaceAllHtmlLink(originalEles, "data-original", domain); replaceAllHtmlLink(hrefEles, "href", domain); imgSrcConverLazyloadSrc(doc); String html = doc.select("body").eq(0).html(); String articleTemplate = html; if (html.indexOf("jquery-lazyload-container") == -1) { articleTemplate = FileUtil.readFile(webPath + "/main/apps/template/article_issue_template.txt"); articleTemplate = articleTemplate.replace("{article_content}", html); } return articleTemplate; } /** * 替换全部链接 * * @param attrEles * @param attr * @param domain * @author 陈锋 * @log 2020年10月19日 */ private void replaceAllHtmlLink(Elements attrEles, String attr, String domain) { for (Element ele : attrEles) { if (ele.tagName().equalsIgnoreCase("img")) { ele.removeAttr("width"); ele.removeAttr("height"); ele.removeAttr("style"); ele.removeAttr("title"); ele.removeAttr("alt"); ele.removeAttr("onload"); ele.removeAttr("border"); ele.removeAttr("vspace"); resetParentsPTagStyle(ele); } String attrValue = ele.attr(attr); if (StringUtil.isNull(attrValue)) { continue; } if (attrValue.startsWith("http://42.247.50.199")) { attrValue = attrValue.replace("http://42.247.50.199", ""); } else { if (shouldKeepOriginalAttrValue(attrValue)) { continue; } } attrValue = FileUtil.replacePathSprit(attrValue); if (domain.endsWith("/") && attrValue.startsWith("/")) { attrValue = domain + attrValue.substring(1); } else { attrValue = domain + attrValue; } if ("href".equals(attr)) { ele.attr("target", "_blank"); } ele.attr(attr, attrValue); } } /** * 只替换 img 标签上的 p 标签,p 标签加 style="text-align: center" * * @param imgEle * @author 陈锋 * @log 2020年10月19日 */ private void resetParentsPTagStyle(Element imgEle) { Element parentEle = imgEle.parent(); for (int i = 0; i < 6; i++) { if (parentEle == null) { return; } if (!parentEle.tagName().equals("p")) { parentEle = parentEle.parent(); } else { parentEle.attr("style", "text-align: center"); break; } } } @Override public boolean isNextServiceFlag() { String nsFlag = this.getRequest().getParameter("nextServiceFormFlag"); return StringUtil.notNull(nsFlag) && nsFlag.equals("true"); } }