package space.apps.moudules.website.services; import java.io.File; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Base64; 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 java.util.regex.Pattern; 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.basic.util.SortOrderUtil; 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 String PREVIEW_RUN_PATH_KEY = "runPath"; private static final String PREVIEW_TITLE_KEY = "title"; private static final String PREVIEW_SOURCE_KEY = "source"; private static final String PREVIEW_DESC_KEY = "desc"; private static final String PREVIEW_NAVIGATION_ID_KEY = "navigationid"; private static final String PREVIEW_WEBSITE_ID_KEY = "websiteid"; private static final String PREVIEW_RELEASE_TIME_KEY = "releaseTime"; private static final Pattern LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN = Pattern.compile( "(?i)(?:https?:)?//(?:ht\\.gzhxtc\\.edu\\.cn|localhost|127\\.0\\.0\\.1|ffkj-[a-z0-9-]+\\.localhost)(?::\\d+)?(/web/upload/[^\"'<>\\s]*)"); private static final Long NAVIGATION_STYLE_TEXT_LIST = 10000L; private static final Long NAVIGATION_STYLE_GRAPHIC_LIST = 10010L; private static final String ARTICLE_DEFAULT_THUMBNAIL = "/main/images/article-default-thumbnail.jpg"; 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); normalizePreviewArticleImages(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 dataEles = doc.select("object[data]"); Elements hrefEles = doc.select("a[href]"); replaceAttrPrefix(srcEles, "src", domain); replaceAttrPrefix(dataEles, "data", 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) { } private boolean verifyArticleImageSources(String htmlContent) throws Exception { if (StringUtil.isNull(htmlContent)) { return true; } Document doc = Jsoup.parseBodyFragment(htmlContent); for (Element image : doc.select("img")) { String src = image.attr("src"); String originalSrc = image.attr("data-original"); boolean temporarySource = (StringUtil.notNull(src) && src.startsWith("blob:")) || (StringUtil.notNull(originalSrc) && originalSrc.startsWith("blob:")); if (temporarySource) { setResponsePackage(getResponseWarningMsgPackage("正文中存在未上传完成或失效的图片,请重新上传")); return false; } } return true; } private void saveArticleContentFiles(Article article, String content) throws Exception { String editPath = WebEditorUtil.createHtmlFile(content); String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath, space.apps.moudules.website.common.ConstVars.domain); String runPath = WebEditorUtil.createHtmlFile(runContent); article.setEditContent(editPath); article.setContent(runPath); } /** * 文章录入 * * @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 (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", false)) { return DEFAULT_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article, false)) { return DEFAULT_FORWARD; } if (!verifyArticleImageSources(content)) { return DEFAULT_FORWARD; } saveArticleContentFiles(article, content); 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); saveArticleSortNumber(gdba, article.getArticleid()); 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; } private void saveArticleSortNumber(GeneralDBAccess gdba, Long articleid) throws Exception { if (StringUtil.isNull(articleid)) { return; } SortOrderUtil.updateSortNumber(gdba, "article", "articleid", articleid, getSortNumberParameter()); } private Long getArticleSortNumber(GeneralDBAccess gdba, Long articleid) throws Exception { if (StringUtil.isNull(articleid)) { return null; } String sql = " select sort_number from article where articleid = :articleid "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("articleid", articleid); Map sortMap = gdba.selectAsMap(sqlCmd); if (sortMap == null || StringUtil.isNull(sortMap.get("sort_number"))) { return null; } return Long.valueOf(sortMap.get("sort_number").toString()); } private Long getSortNumberParameter() { return SortOrderUtil.parseSortNumber(getParameter("sortNumber")); } private Article getArticleById(GeneralDBAccess gdba, Long articleid) throws Exception { Article article = new Article(); article.setArticleid(articleid); gdba.selectById(article); if (article.getDcode() == null) { throw new Exception("文章不存在"); } return article; } /** * 设置文章申请服务 * * @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 = getArticleById(gdba, getParameterToLong("articleid")); if (!Long.valueOf(dataStatusCode.INSERT.getCode()).equals(a2.getDcode()) && !Long.valueOf(dataStatusCode.STAY_SUBMIT.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 = getArticleById(gdba, a2.getArticleid()); PojoUtil.formatRequest(getRequest(), article); WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目"); if (wn == null) { return DEFAULT_FORWARD; } if (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", false)) { return DEFAULT_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article, false)) { return DEFAULT_FORWARD; } if (!verifyArticleImageSources(content)) { return DEFAULT_FORWARD; } article.setSticktop("yes".equals(top) ? 1L : 0L); ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), GsonUtil.toJson(a2)); saveArticleContentFiles(article, content); 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); saveArticleSortNumber(gdba, article.getArticleid()); 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 { return WebsiteTemplateNavUtil.selectNavigationById(gdba, navigationId); } 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, boolean allowLegacyDefaultThumbnail) 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 (!verifyNavigationThumbnailRequired(gdba, wn, article, "抄送栏目", allowLegacyDefaultThumbnail)) { return false; } } return true; } private boolean verifyNavigationThumbnailRequired(GeneralDBAccess gdba, WebsiteNavigation wn, Article article, String targetName, boolean allowLegacyDefaultThumbnail) throws Exception { if (wn == null || NAVIGATION_STYLE_TEXT_LIST.equals(wn.getWnlscode())) { return true; } if (article != null && StringUtil.notNull(article.getThumbnail())) { return true; } if (allowLegacyDefaultThumbnail && article != null) { article.setThumbnail(ARTICLE_DEFAULT_THUMBNAIL); 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 = getArticleById(gdba, getParameterToLong("articleid")); boolean legacyThumbnailMissing = StringUtil.isNull(article.getThumbnail()); PojoUtil.formatRequest(getRequest(), article); WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目"); if (wn == null) { return TIPS_FORWARD; } if (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", legacyThumbnailMissing)) { return TIPS_FORWARD; } if (!verifyArticleCopyNavigationList(gdba, navIdList, article, legacyThumbnailMissing)) { return TIPS_FORWARD; } if (!verifyArticleImageSources(content)) { return TIPS_FORWARD; } article.setSticktop("yes".equals(top) ? 1L : 0L); Article a2 = getArticleById(gdba, article.getArticleid()); ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), buildArticleChangeLogContent(a2, nowTimestamp)); verifyArticleUrl(article, a2, wn); saveArticleContentFiles(article, content); 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); saveArticleSortNumber(gdba, article.getArticleid()); 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); } } } private List> getArticleFlowList(GeneralDBAccess gdba, Long articleid) throws Exception { String sql = " select ap.applyid, ap.ascode, " + " coalesce(asc1.name, '未知状态') as statusName, " + " coalesce(initp.name, '未知') as initiatorName, " + " coalesce((select group_concat(distinct cp.name order by cp.name separator '、') " + " from audit cau join person cp on cp.personid = cau.personid " + " where ap.ascode = 11 and cau.applyid = ap.applyid and cau.dcode = 31 " + " and cau.audit_time is null and cau.acode in (51, 101)), '') as currentAuditors, " + " case " + " when lower(ap.flow_key) like '%articlechange%' then '变动审核' " + " when lower(ap.flow_key) like '%articledisable%' then '停用审核' " + " when lower(ap.flow_key) like '%articleenable%' then '启用审核' " + " when lower(ap.flow_key) like '%articlerelease%' then '发布审核' " + " else '文章审核' " + " end as flowName, " + " case " + " when ap.ascode = 11 then 'warning' " + " when ap.ascode in (41, 51) then 'success' " + " when ap.ascode in (21, 31, 61) then 'danger' " + " else 'info' " + " end as statusType, " + " date_format(ap.create_time, '%Y-%m-%d %H:%i:%s') as createTime, " + " ifnull(date_format(ap.end_time, '%Y-%m-%d %H:%i:%s'), '') as endTime, " + " ifnull((select au.auditid from audit au " + " where au.applyid = ap.applyid and au.dcode <> 72 " + " order by case " + " when ap.ascode = 11 and au.dcode = 31 and au.audit_time is null and au.acode in (51, 101) then 0 " + " when au.audit_time is not null then 1 " + " else 2 end, " + " ifnull(au.steps, 0) desc, au.auditid desc limit 1), 0) as auditid " + " from apply ap " + " left join apply_status_code asc1 on asc1.apply_status_code = ap.ascode " + " left join person initp on initp.personid = ap.personid " + " where ap.dcode <> 72 and ap.table_name = 'article' and ap.table_key = 'articleid' " + " and ap.table_key_value = :articleid " + " order by case when ap.ascode = 11 then 0 else 1 end, ap.create_time desc, ap.applyid desc "; SqlCommandImpl sqlCmd = new SqlCommandImpl(sql); sqlCmd.setString("articleid", articleid); return gdba.selectAsMapList(sqlCmd); } /** * 文章信息 * * @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("sortNumber", getArticleSortNumber(gdba, article.getArticleid())); setRequestAttribute("navAllName", navAllName); setRequestAttribute("copyNav", GsonUtil.toJson(articleCopyList)); setRequestAttribute("articleFlowList", GsonUtil.toJson(getArticleFlowList(gdba, article.getArticleid()))); WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid()); String articleContentForPreview; try { articleContentForPreview = FileUtil.readFile(getWebRootPath() + article.getContent()); setRequestAttribute("body", articleContentForPreview); } catch (Exception e) { articleContentForPreview = "内容文件不存在或已被删除"; setRequestAttribute("body", articleContentForPreview); } setRequestAttribute("infoPreviewHtmlB64", Base64.getEncoder().encodeToString( buildArticleInfoPreviewHtml(article, website, navigation, articleContentForPreview) .getBytes(StandardCharsets.UTF_8))); 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.sort_number, a.sticktop, a.release_time, a.read_count, a.create_pid, a.last_change_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, ").append(SortOrderUtil.articleSort("a")); } else if ("sort_top".equals(sort)) { sqlBuilder.append(" order by dcode asc, ") .append(SortOrderUtil.validSortRank("a.sort_number")).append(", ") .append("case when ").append(SortOrderUtil.validSortCondition("a.sort_number")) .append(" then a.sort_number else null end asc, read_count desc, release_time desc, articleid desc "); } else if ("sort_bottom".equals(sort)) { sqlBuilder.append(" order by dcode asc, ") .append(SortOrderUtil.validSortRank("a.sort_number")).append(", ") .append("case when ").append(SortOrderUtil.validSortCondition("a.sort_number")) .append(" then a.sort_number else null end asc, read_count asc, release_time desc, articleid desc "); } 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"); String title = getParameterNotXSS("title"); String source = getParameterNotXSS("source"); String desc = getParameterNotXSS("desc"); 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, buildPreviewInfo(runPath, wn, title, source, desc)); 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 previewObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key); String previewPath = getPreviewRunPath(previewObj); File previewFile = getSafePreviewFile(previewPath); if (previewFile == null) { writePreviewUnavailable(); return; } if (previewObj instanceof Map) { renderArticlePreviewPage(previewObj, previewFile); return; } write(buildArticlePreviewHtml(null, null, FileUtil.readFile(previewFile.getPath()))); } /** * 文章信息弹窗内容区 PC 预览(与三端预览 PC 端同源)。 */ public void infoPreviewView() throws Exception { getResponse().setContentType("text/html;charset=UTF-8"); Long articleid = getParameterToLong("articleid"); if (articleid == null || articleid <= 0) { writePreviewUnavailable(); return; } GeneralDBAccess gdba = getGdbaInstance(); Article article = new Article(); article.setArticleid(articleid); gdba.selectById(article); Website website = new Website(); website.setWebsiteid(article.getWebsiteid()); gdba.selectById(website); WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid()); String articleContent; try { articleContent = FileUtil.readFile(getWebRootPath() + article.getContent()); } catch (Exception e) { writePreviewUnavailable(); return; } write(buildArticleInfoPreviewHtml(article, website, navigation, articleContent)); } private String buildArticleInfoPreviewHtml(Article article, Website website, WebsiteNavigation navigation, String articleContent) { Map previewInfo = new HashMap(); previewInfo.put(PREVIEW_TITLE_KEY, article.getTitle()); previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(article.getSource(), website.getName())); previewInfo.put(PREVIEW_RELEASE_TIME_KEY, formatArticleReleaseTime(article.getReleaseTime())); previewInfo.put(PREVIEW_NAVIGATION_ID_KEY, article.getNavigationid() == null ? "" : article.getNavigationid().toString()); previewInfo.put(PREVIEW_WEBSITE_ID_KEY, article.getWebsiteid() == null ? "" : article.getWebsiteid().toString()); return buildArticlePreviewHtml(previewInfo, navigation, website, articleContent); } private String formatArticleReleaseTime(Timestamp releaseTime) { if (releaseTime == null) { return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm"); } try { String formatted = DateTimeUtil.formatDateYMdHms(releaseTime); return StringUtil.isNull(formatted) ? DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm") : formatted; } catch (ParseException e) { return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm"); } } private Map buildPreviewInfo(String runPath, WebsiteNavigation navigation, String title, String source, String desc) { Map previewInfo = new HashMap(); previewInfo.put(PREVIEW_RUN_PATH_KEY, runPath); previewInfo.put(PREVIEW_TITLE_KEY, firstNotBlank(title, "正文预览")); previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(source, "")); previewInfo.put(PREVIEW_DESC_KEY, firstNotBlank(desc, "")); previewInfo.put(PREVIEW_NAVIGATION_ID_KEY, navigation == null || navigation.getNavigationid() == null ? "" : navigation.getNavigationid().toString()); previewInfo.put(PREVIEW_WEBSITE_ID_KEY, navigation == null || navigation.getWebsiteid() == null ? "" : navigation.getWebsiteid().toString()); return previewInfo; } @SuppressWarnings("rawtypes") private String getPreviewRunPath(Object previewObj) { if (previewObj instanceof Map) { Object runPath = ((Map) previewObj).get(PREVIEW_RUN_PATH_KEY); return runPath == null ? "" : runPath.toString(); } return previewObj == null ? "" : previewObj.toString(); } @SuppressWarnings("rawtypes") private void renderArticlePreviewPage(Object previewObj, File previewFile) throws Exception { Map previewInfo = (Map) previewObj; GeneralDBAccess gdba = getGdbaInstance(); Long navigationId = parseLong(previewInfo.get(PREVIEW_NAVIGATION_ID_KEY)); Long websiteId = parseLong(previewInfo.get(PREVIEW_WEBSITE_ID_KEY)); WebsiteNavigation navigation = navigationId == null ? null : getWebsiteNavigationById(gdba, navigationId); if (navigation != null && navigation.getWebsiteid() != null) { websiteId = navigation.getWebsiteid(); } Website website = websiteId == null ? null : WebsiteUtil.getWebsiteByID(gdba, websiteId); String articleContent = restorePreviewLazyImages(FileUtil.readFile(previewFile.getPath())); write(buildArticlePreviewHtml(previewInfo, navigation, website, articleContent)); } private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, Website website, String articleContent) { String title = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_TITLE_KEY), "正文预览"); String source = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_SOURCE_KEY), website == null ? "" : website.getName()); String releaseTime = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_RELEASE_TIME_KEY), DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm")); String content = restorePreviewLazyImages(firstNotBlank(articleContent, "")); StringBuilder html = new StringBuilder(); html.append("") .append("") .append("") .append("") .append("") .append("
") .append("
"); html.append("

").append(escapeHtml(title)).append("

") .append("
") .append("
") .append(content) .append("
") .append("") .append("") .append(""); return html.toString(); } private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, String articleContent) { return buildArticlePreviewHtml(previewInfo, navigation, null, articleContent); } private String restorePreviewLazyImages(String articleContent) { if (StringUtil.isNull(articleContent)) { return articleContent; } Document doc = Jsoup.parseBodyFragment(normalizeLocalUploadResourceUrl(articleContent)); Elements lazyImages = doc.select("img[data-original]"); for (Element image : lazyImages) { if (StringUtil.isNull(image.attr("src"))) { image.attr("src", image.attr("data-original")); } } normalizePreviewArticleImages(doc); doc.select("script").remove(); unwrapArticleContentContainer(doc); return doc.body().html(); } private void unwrapArticleContentContainer(Document doc) { Elements wrappers = doc.select("#jquery-lazyload-container, div.ck-content"); for (Element wrapper : wrappers) { wrapper.unwrap(); } } private void normalizePreviewArticleImages(Document doc) { Elements figures = doc.select("figure.image, figure.image_resized, figure:has(img), .ck-content .image"); for (Element figure : figures) { figure.removeAttr("width"); figure.removeAttr("height"); figure.attr("style", "display:block;width:100%;max-width:100%;margin:18px 0;text-align:left;"); } Elements images = doc.select("img"); for (Element image : images) { image.removeAttr("width"); image.removeAttr("height"); image.removeAttr("hspace"); image.removeAttr("vspace"); image.removeAttr("border"); image.attr("style", "display:block;width:100%;max-width:100%;height:auto;margin:18px 0;box-sizing:border-box;"); } Elements mediaBlocks = doc.select("p:has(img), div:has(img), figure:has(img)"); for (Element block : mediaBlocks) { String style = block.attr("style"); style = stripArticleImageStyleProperty(style, "width"); style = stripArticleImageStyleProperty(style, "max-width"); style = stripArticleImageStyleProperty(style, "margin"); style = stripArticleImageStyleProperty(style, "text-align"); style = stripArticleImageStyleProperty(style, "text-indent"); block.attr("style", joinArticleImageStyle(style, "text-align:left;text-indent:0;")); } } private String stripArticleImageStyleProperty(String style, String property) { if (StringUtil.isNull(style) || StringUtil.isNull(property)) { return style == null ? "" : style; } return style.replaceAll("(?i)" + Pattern.quote(property) + "\\s*:[^;\"']*(;|$)", "$1").trim(); } private String joinArticleImageStyle(String baseStyle, String appendStyle) { String normalizedBase = baseStyle == null ? "" : baseStyle.trim(); if (normalizedBase.length() > 0 && !normalizedBase.endsWith(";")) { normalizedBase += ";"; } return normalizedBase + appendStyle; } private String normalizeLocalUploadResourceUrl(String content) { if (StringUtil.isNull(content) || content.indexOf("/web/upload/") < 0) { return content; } return LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN.matcher(content).replaceAll("$1"); } private String escapeHtml(String value) { if (value == null) { return ""; } return value.replace("&", "&").replace("<", "<").replace(">", ">") .replace("\"", """).replace("'", "'"); } private Long parseLong(Object value) { if (value == null || StringUtil.isNull(value.toString())) { return null; } try { return Long.valueOf(value.toString()); } catch (Exception e) { return null; } } private String firstNotBlank(Object value, String fallback) { if (value == null) { return fallback; } String text = value.toString().trim(); return text.length() == 0 ? fallback : text; } 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 mediaSrcEles = doc.select("iframe[src], embed[src], object[src]"); Elements objectDataEles = doc.select("object[data]"); Elements hrefEles = doc.select("a[href]"); replaceAllHtmlLink(srcEles, "src", domain); replaceAllHtmlLink(originalEles, "data-original", domain); replaceAllHtmlLink(mediaSrcEles, "src", domain); replaceAllHtmlLink(objectDataEles, "data", domain); replaceAllHtmlLink(hrefEles, "href", domain); imgSrcConverLazyloadSrc(doc); normalizePreviewArticleImages(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"); } }