| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960 |
- 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<String, Object> 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<String, Object> 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<String> navIdSet = new HashSet<String>();
- 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<String, Object> 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<String, Object> 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<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> navigationList) throws Exception {
- for (Map<String, Object> 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<WebsiteNavigation> 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<String, Object> getNavigationMap(GeneralDBAccess gdba, List<Map<String, Object>> navigationList)
- throws Exception {
- Map<String, Object> retMap = new HashMap<String, Object>();
- if (navigationList == null || navigationList.size() == 0) {
- retMap.put("data", new ArrayList<Map<String, Object>>());
- return retMap;
- }
- Set<String> websiteSet = new HashSet<String>();
- Map<String, List<Map<String, Object>>> websiteNavigationMap = new LinkedHashMap<String, List<Map<String, Object>>>();
- for (Map<String, Object> map : navigationList) {
- String website = map.get("websiteid").toString();
- websiteSet.add(website);
- List<Map<String, Object>> websiteNavigationList = websiteNavigationMap.get(website);
- if (websiteNavigationList == null) {
- websiteNavigationList = new ArrayList<Map<String, Object>>();
- websiteNavigationMap.put(website, websiteNavigationList);
- }
- websiteNavigationList.add(map);
- }
- if (websiteSet.size() > 1) {
- List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
- for (String websiteId : websiteNavigationMap.keySet()) {
- Website w = new Website();
- w.setWebsiteid(Long.valueOf(websiteId));
- gdba.selectById(w);
- Map<String, Object> map = new HashMap<String, Object>();
- 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<Map<String, Object>> buildNavigationTree(List<Map<String, Object>> navigationList) {
- Map<String, Map<String, Object>> navigationMap = new LinkedHashMap<String, Map<String, Object>>();
- for (Map<String, Object> navigation : navigationList) {
- Map<String, Object> item = new HashMap<String, Object>(navigation);
- item.remove("children");
- navigationMap.put(item.get("navigationid").toString(), item);
- }
- List<Map<String, Object>> rootList = new ArrayList<Map<String, Object>>();
- for (Map<String, Object> navigation : navigationMap.values()) {
- Object parentNid = navigation.get("parent_nid");
- Map<String, Object> parent = parentNid == null ? null : navigationMap.get(parentNid.toString());
- if (parent == null) {
- rootList.add(navigation);
- continue;
- }
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
- if (children == null) {
- children = new ArrayList<Map<String, Object>>();
- parent.put("children", children);
- }
- children.add(navigation);
- }
- setDisabledNavigationList(rootList);
- return rootList;
- }
- private void setDisabledNavigationList(List<Map<String, Object>> navigationList) {
- for (Map<String, Object> navigation : navigationList) {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> children = (List<Map<String, Object>>) navigation.get("children");
- if (children != null && children.size() > 0) {
- setDisabledNavigationList(children);
- continue;
- }
- if (!isArticleTargetWntcode(navigation.get("wntcode"))) {
- navigation.put("disabled", true);
- }
- }
- }
- private List<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> data = new HashMap<String, Object>();
- 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<String, Object> data = new HashMap<String, Object>();
- 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<Map<String, Object>> 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<Map<String, Object>> articleList = gdba.selectAsMapList(sqlCmd, getAppsPageBean());
- for (Map<String, Object> map : articleList) {
- // 校验是否拥有该网站的管理权限
- for (Map<String, Object> 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<String> navIdSet = new HashSet<String>();
- 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<Map<String, Object>> 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<String, Object> retMap = new HashMap<String, Object>();
- 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<String, Object> previewInfo = new HashMap<String, Object>();
- 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<String, Object> buildPreviewInfo(String runPath, WebsiteNavigation navigation, String title,
- String source, String desc) {
- Map<String, Object> previewInfo = new HashMap<String, Object>();
- 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("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">")
- .append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">")
- .append("<link rel=\"stylesheet\" href=\"/main/ffkj-portal/portal-source.css?v=20260703-article-image-fit-v2\">")
- .append("<link rel=\"stylesheet\" href=\"/apps/space/css/space.editor.css?v=20260703-article-image-fit-v2\">")
- .append("<style>")
- .append("html{height:100%;overflow:hidden;}")
- .append("body{margin:0;height:100%;overflow-x:hidden;overflow-y:auto;background:#f5f7fa;color:#1f2937;font-family:Arial,'Microsoft YaHei',sans-serif;}")
- .append(".preview-article{box-sizing:border-box;max-width:900px;margin:0 auto;padding:36px 32px;background:#fff;min-height:100%;}")
- .append(".preview-article.article-panel{padding:36px 32px!important;}")
- .append(".preview-article-header{margin:0 0 22px;padding:0 0 18px;border-bottom:3px solid #a40011;}")
- .append(".preview-article-title{margin:0;color:#a40011;font-size:30px;line-height:1.35;font-weight:700;letter-spacing:0;}")
- .append(".preview-article-meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:14px;color:#666;font-size:14px;line-height:1.5;}")
- .append(".preview-article-body{font-size:16px;line-height:1.9;color:#333;}")
- .append(".preview-article-body .ck-content,#jquery-lazyload-container.ck-content{width:100%!important;margin:0!important;padding:0!important;}")
- .append(".preview-article-body img,.article-body img,.preview-article-body .ck-content img,.article-body .ck-content img,.preview-article-body figure.image img,.article-body figure.image img,.preview-article-body .ck-content .image img,.article-body .ck-content .image img{display:block;width:100%!important;max-width:100%!important;height:auto!important;margin:18px 0!important;box-sizing:border-box;}")
- .append(".preview-article-body figure.image,.article-body figure.image,.preview-article-body figure:has(img),.article-body figure:has(img),.preview-article-body .ck-content .image,.article-body .ck-content .image,.preview-article-body .ck-content figure,.article-body .ck-content figure{display:block!important;width:100%!important;max-width:100%!important;margin:18px 0!important;padding:0!important;text-align:left!important;}")
- .append(".preview-article-body p:has(img),.preview-article-body div:has(img),.preview-article-body figure:has(img),")
- .append(".article-body p:has(img),.article-body div:has(img),.article-body figure:has(img),")
- .append(".preview-article-body .ck-content p:has(img),.preview-article-body .ck-content div:has(img),.article-body .ck-content p:has(img),.article-body .ck-content div:has(img){text-align:left!important;text-indent:0!important;}")
- .append(".preview-article-body video,.preview-article-body iframe,.preview-article-body object,.preview-article-body embed,.article-body video,.article-body iframe,.article-body object,.article-body embed{display:block;width:100%!important;max-width:100%!important;margin:18px 0!important;}")
- .append(".preview-article-body figure.space-editor-pdf-viewer{max-width:100%;}")
- .append(".preview-article-body iframe.space-editor-pdf-frame{width:100%;height:min(78vh,720px);min-height:480px;}")
- .append("@media (max-width: 700px){.preview-article{padding:24px 18px;}.preview-article-title{font-size:24px;}.preview-article-body iframe.space-editor-pdf-frame{min-height:420px;}}")
- .append("</style></head><body>")
- .append("<article class=\"preview-article article-panel school-article-panel\">")
- .append("<header class=\"preview-article-header article-header\">");
- html.append("<h1 class=\"preview-article-title\">").append(escapeHtml(title)).append("</h1>")
- .append("<div class=\"preview-article-meta\">")
- .append("<span>").append(escapeHtml(releaseTime)).append("</span>");
- if (!StringUtil.isNull(source)) {
- html.append("<span>来源:").append(escapeHtml(source)).append("</span>");
- }
- html.append("</div></header>")
- .append("<div class=\"preview-article-body article-body\" data-article-preview=\"true\">")
- .append(content)
- .append("</div></article>")
- .append("<script src=\"/apps/space/js/secure-pdf.js?v=20260709-pdf-secure\"></script>")
- .append("<script>(function(){var root=document.querySelector('.article-body,[data-article-preview]');if(!root){return;}function normalizeNode(node){if(!node){return;}node.style.setProperty('display','block','important');node.style.setProperty('width','100%','important');node.style.setProperty('max-width','100%','important');node.style.setProperty('margin','18px 0','important');node.style.setProperty('padding','0','important');node.style.setProperty('text-align','left','important');}root.querySelectorAll('.ck-content .image,figure.image,figure').forEach(function(fig){if(!fig.querySelector('img')){return;}normalizeNode(fig);});root.querySelectorAll('img').forEach(function(img){img.style.setProperty('display','block','important');img.style.setProperty('width','100%','important');img.style.setProperty('max-width','100%','important');img.style.setProperty('height','auto','important');img.style.setProperty('margin','18px 0','important');var parent=img.closest('p,div,figure,.image');if(parent){parent.style.setProperty('text-align','left','important');parent.style.setProperty('text-indent','0','important');}});})();</script>")
- .append("</body></html>");
- 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("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>"
- + "body{margin:0;font-family:Arial,'Microsoft YaHei',sans-serif;background:#f5f7fa;color:#606266;}"
- + ".msg{padding:80px 20px;text-align:center;font-size:14px;}"
- + "</style></head><body><div class=\"msg\">预览内容不存在,请刷新预览后再查看。</div></body></html>");
- }
- // 测试的服务
- /**
- * 重置文章运行文件,主要是替换链接的域名,固定替换为 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<Article> 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");
- }
- }
|