ArticleService.java 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. package space.apps.moudules.website.services;
  2. import java.io.File;
  3. import java.net.URLEncoder;
  4. import java.nio.charset.StandardCharsets;
  5. import java.sql.Timestamp;
  6. import java.text.ParseException;
  7. import java.util.ArrayList;
  8. import java.util.Base64;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.LinkedHashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Set;
  15. import java.util.regex.Pattern;
  16. import com.google.gson.JsonObject;
  17. import com.google.gson.JsonParser;
  18. import org.apache.logging.log4j.LogManager;
  19. import org.apache.logging.log4j.Logger;
  20. import org.jsoup.Jsoup;
  21. import org.jsoup.nodes.Document;
  22. import org.jsoup.nodes.Element;
  23. import org.jsoup.select.Elements;
  24. import apps.pojo.Article;
  25. import apps.pojo.ArticleCopy;
  26. import apps.pojo.ArticleJumpTypeCode;
  27. import apps.pojo.Website;
  28. import apps.pojo.WebsiteNavigation;
  29. import space.apps.common.ConstVars.dataStatusCode;
  30. import space.apps.moudules.basic.util.SortOrderUtil;
  31. import space.apps.moudules.sys.utils.ChangeLogUtil;
  32. import space.apps.moudules.website.common.ConstVars.articleJumpTypeCode;
  33. import space.apps.moudules.website.common.ConstVars.articleStatusCode;
  34. import space.apps.moudules.website.template.util.WebsiteTemplateArticleUtil;
  35. import space.apps.moudules.website.template.util.WebsiteTemplateNavUtil;
  36. import space.apps.moudules.website.template.util.WebsiteUtil;
  37. import space.apps.moudules.website.util.AppWebsiteManageUtil;
  38. import space.core.apps.common.BaseTransaction;
  39. import space.core.apps.common.ConstVars;
  40. import space.core.apps.common.ScheduleImpl;
  41. import space.core.apps.common.bean.AppUser;
  42. import space.core.apps.common.bean.NextService;
  43. import space.core.apps.common.bean.ResponsePackage;
  44. import space.core.apps.util.GdbaQueryUtil;
  45. import space.core.apps.util.NextServiceUtil;
  46. import space.core.apps.util.WebEditorUtil;
  47. import space.core.common.utils.DateTimeUtil;
  48. import space.core.common.utils.FileUtil;
  49. import space.core.common.utils.GsonUtil;
  50. import space.core.common.utils.PojoUtil;
  51. import space.core.common.utils.StringUtil;
  52. import space.core.db.jdbc.GeneralDBAccess;
  53. import space.core.db.jdbc.SqlCommandImpl;
  54. /**
  55. * 文章服务类
  56. *
  57. * @author SPACE
  58. * @date 2020年02月08日
  59. */
  60. public class ArticleService extends BaseTransaction {
  61. static Logger log = LogManager.getLogger(ArticleService.class);
  62. private static final long serialVersionUID = 1L;
  63. private static final String ARTICLE_PREVIEW_SESSION_PREFIX = "articlePreviewPath_";
  64. private static final String PREVIEW_RUN_PATH_KEY = "runPath";
  65. private static final String PREVIEW_TITLE_KEY = "title";
  66. private static final String PREVIEW_SOURCE_KEY = "source";
  67. private static final String PREVIEW_DESC_KEY = "desc";
  68. private static final String PREVIEW_NAVIGATION_ID_KEY = "navigationid";
  69. private static final String PREVIEW_WEBSITE_ID_KEY = "websiteid";
  70. private static final String PREVIEW_RELEASE_TIME_KEY = "releaseTime";
  71. private static final Pattern LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN = Pattern.compile(
  72. "(?i)(?:https?:)?//(?:ht\\.gzhxtc\\.edu\\.cn|localhost|127\\.0\\.0\\.1|ffkj-[a-z0-9-]+\\.localhost)(?::\\d+)?(/web/upload/[^\"'<>\\s]*)");
  73. private static final Long NAVIGATION_STYLE_TEXT_LIST = 10000L;
  74. private static final Long NAVIGATION_STYLE_GRAPHIC_LIST = 10010L;
  75. private static final String ARTICLE_DEFAULT_THUMBNAIL = "/main/images/article-default-thumbnail.jpg";
  76. private static final String COLLEGE_RED_TEMPLATE_ID_CODE = "ffkjcollegered1";
  77. private static final String ARTICLE_PUBLISHED_HISTORY_ROOT = "/web/upload/article-history/";
  78. private static final String PUBLISHED_CONTENT_SNAPSHOT_FIELD = "publishedContentSnapshot";
  79. private static final String PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD = "publishedEditContentSnapshot";
  80. /**
  81. * 转换文章内容 html 里的链接
  82. *
  83. * @param path
  84. * @param domain
  85. * @return
  86. * @throws Exception
  87. * @author 陈锋
  88. * @log 2020年10月16日
  89. */
  90. private String converArticleContentHtmlLink(String path, String domain) throws Exception {
  91. File input = new File(path);
  92. Document doc = Jsoup.parse(input, "UTF-8", "");
  93. replaceHtmlLink(doc, domain);
  94. imgSrcConverLazyloadSrc(doc);
  95. normalizePreviewArticleImages(doc);
  96. String html = doc.select("body").eq(0).html();
  97. String articleTemplate = FileUtil.readFile(
  98. getWebRootPath() + space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_PATH);
  99. articleTemplate = articleTemplate
  100. .replace(space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_CONTENT_KEY, html);
  101. return articleTemplate;
  102. }
  103. /**
  104. * 替换 html 的链接
  105. *
  106. * @param doc
  107. * @param domain
  108. * @author 陈锋
  109. * @log 2020年10月16日
  110. */
  111. private void replaceHtmlLink(Document doc, String domain) {
  112. Elements srcEles = doc.select("[src]");
  113. Elements dataEles = doc.select("object[data]");
  114. Elements hrefEles = doc.select("a[href]");
  115. replaceAttrPrefix(srcEles, "src", domain);
  116. replaceAttrPrefix(dataEles, "data", domain);
  117. replaceAttrPrefix(hrefEles, "href", domain);
  118. }
  119. /**
  120. * 替换属性的前缀
  121. *
  122. * @param attrEles 属性标签集合
  123. * @param attr 属性名
  124. * @param prefix 前缀
  125. * @author 陈锋
  126. * @log 2020年10月16日
  127. */
  128. private void replaceAttrPrefix(Elements attrEles, String attr, String prefix) {
  129. for (Element ele : attrEles) {
  130. String attrValue = ele.attr(attr);
  131. if (StringUtil.isNull(attrValue)) {
  132. continue;
  133. }
  134. if (shouldKeepOriginalAttrValue(attrValue)) {
  135. continue;
  136. }
  137. if (prefix.endsWith("/") && attrValue.startsWith("/")) {
  138. attrValue = prefix + attrValue.substring(1);
  139. } else {
  140. attrValue = prefix + attrValue;
  141. }
  142. ele.attr(attr, attrValue);
  143. }
  144. }
  145. private boolean shouldKeepOriginalAttrValue(String attrValue) {
  146. if (StringUtil.isNull(attrValue)) {
  147. return true;
  148. }
  149. String value = attrValue.trim().toLowerCase();
  150. return value.startsWith("http://") || value.startsWith("https://") || value.startsWith("//")
  151. || value.startsWith("data:") || value.startsWith("blob:") || value.startsWith("mailto:")
  152. || value.startsWith("tel:") || value.startsWith("javascript:") || value.startsWith("#");
  153. }
  154. /**
  155. * img 标签的 src 转为 jquery.lazyload.js 的懒加载的 data-original 属性
  156. *
  157. * @param doc
  158. * @author 陈锋
  159. * @log 2020年10月16日
  160. */
  161. private void imgSrcConverLazyloadSrc(Document doc) {
  162. Elements srcEles = doc.select("img[src]");
  163. int i = 0;
  164. for (Element ele : srcEles) {
  165. i++;
  166. if (i <= 3) {
  167. continue;
  168. }
  169. String srcValue = ele.attr("src");
  170. ele.removeAttr("src");
  171. ele.attr("data-original", srcValue);
  172. }
  173. }
  174. /**
  175. * 保留手填摘要;未填写摘要时允许为空,不再从正文自动提取。
  176. *
  177. * @param article 文章
  178. * @param htmlContent html 正文内容
  179. * @author 陈锋
  180. * @log 2020年10月19日
  181. */
  182. private void saveArticleDesc(Article article, String htmlContent) {
  183. }
  184. private boolean verifyArticleImageSources(String htmlContent) throws Exception {
  185. if (StringUtil.isNull(htmlContent)) {
  186. return true;
  187. }
  188. Document doc = Jsoup.parseBodyFragment(htmlContent);
  189. for (Element image : doc.select("img")) {
  190. String src = image.attr("src");
  191. String originalSrc = image.attr("data-original");
  192. boolean temporarySource = (StringUtil.notNull(src) && src.startsWith("blob:"))
  193. || (StringUtil.notNull(originalSrc) && originalSrc.startsWith("blob:"));
  194. if (temporarySource) {
  195. setResponsePackage(getResponseWarningMsgPackage("正文中存在未上传完成或失效的图片,请重新上传"));
  196. return false;
  197. }
  198. }
  199. return true;
  200. }
  201. private void saveArticleContentFiles(Article article, String content) throws Exception {
  202. String editPath = WebEditorUtil.createHtmlFile(content);
  203. String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath,
  204. space.apps.moudules.website.common.ConstVars.domain);
  205. String runPath = WebEditorUtil.createHtmlFile(runContent);
  206. article.setEditContent(editPath);
  207. article.setContent(runPath);
  208. }
  209. /**
  210. * 文章录入
  211. *
  212. * @return
  213. * @throws Exception
  214. * @author SPACE
  215. * @date 2020年02月09日
  216. */
  217. public String add() throws Exception {
  218. AppUser appUser = getAppUser();
  219. GeneralDBAccess gdba = getGdbaInstance();
  220. Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
  221. String top = getParameter("top");
  222. String timeSwitch = getParameter("timeSwitch");
  223. String content = getParameterNotXSS("body");
  224. Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class);
  225. String navIdList = getParameter("navIdList");
  226. WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
  227. if (wn == null) {
  228. return DEFAULT_FORWARD;
  229. }
  230. if (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", false)) {
  231. return DEFAULT_FORWARD;
  232. }
  233. if (!verifyArticleCopyNavigationList(gdba, navIdList, article, false)) {
  234. return DEFAULT_FORWARD;
  235. }
  236. if (!verifyArticleImageSources(content)) {
  237. return DEFAULT_FORWARD;
  238. }
  239. saveArticleContentFiles(article, content);
  240. article.setUnitid(appUser.getUnitId());
  241. article.setDcode(dataStatusCode.INSERT.getCode());
  242. article.setCreatePid(appUser.getUserId());
  243. article.setLastChangePid(appUser.getUserId());
  244. article.setCreateTime(nowTimestamp);
  245. // article.setReleaseTime(nowTimestamp);
  246. article.setLastChangeTime(nowTimestamp);
  247. article.setSticktop("yes".equals(top) ? 1L : 0L);
  248. article.setAscode(articleStatusCode.STAY_RELEASE.getCode());// 必填的
  249. article.setWebsiteid(wn.getWebsiteid());
  250. article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
  251. if (!article.getAjtcode().equals(10020L)) {
  252. article.setUrl(WebsiteTemplateArticleUtil.getArticleURL(wn));
  253. }
  254. // if (StringUtil.isNull(article.getReleaseTime())) {
  255. // article.setReleaseTime(nowTimestamp);
  256. // }
  257. saveArticleDesc(article, content);
  258. gdba.insertByBean(article);
  259. saveArticleSortNumber(gdba, article.getArticleid());
  260. saveArticleCopy(gdba, article, appUser, navIdList);
  261. initArticleSticktopSchedule(gdba, article, appUser);
  262. initArticleReleaseTaskSchedule(gdba, article, appUser);
  263. gdba.updateById(article);
  264. setArticleApplyService(article.getArticleid());
  265. gdba.commit();
  266. setResponsePackage(getResponseSuccessMsgPackage());
  267. return DEFAULT_FORWARD;
  268. }
  269. private void saveArticleSortNumber(GeneralDBAccess gdba, Long articleid) throws Exception {
  270. if (StringUtil.isNull(articleid)) {
  271. return;
  272. }
  273. SortOrderUtil.updateSortNumber(gdba, "article", "articleid", articleid, getSortNumberParameter());
  274. }
  275. private Long getArticleSortNumber(GeneralDBAccess gdba, Long articleid) throws Exception {
  276. if (StringUtil.isNull(articleid)) {
  277. return null;
  278. }
  279. String sql = " select sort_number from article where articleid = :articleid ";
  280. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  281. sqlCmd.setString("articleid", articleid);
  282. Map<String, Object> sortMap = gdba.selectAsMap(sqlCmd);
  283. if (sortMap == null || StringUtil.isNull(sortMap.get("sort_number"))) {
  284. return null;
  285. }
  286. return Long.valueOf(sortMap.get("sort_number").toString());
  287. }
  288. private Long getSortNumberParameter() {
  289. return SortOrderUtil.parseSortNumber(getParameter("sortNumber"));
  290. }
  291. private Article getArticleById(GeneralDBAccess gdba, Long articleid) throws Exception {
  292. Article article = new Article();
  293. article.setArticleid(articleid);
  294. gdba.selectById(article);
  295. if (article.getDcode() == null) {
  296. throw new Exception("文章不存在");
  297. }
  298. return article;
  299. }
  300. /**
  301. * 设置文章申请服务
  302. *
  303. * @param articleid 文章 id
  304. * @author 陈锋
  305. * @log 2020年12月8日 下午8:28:18
  306. */
  307. private void setArticleApplyService(Long articleid) {
  308. // 设置下一个服务对象
  309. if (isNextServiceFlag()) {
  310. Map<String, Object> paramsMap = NextServiceUtil.newHashMap();
  311. paramsMap.put("articleid", articleid);
  312. NextService nextService = NextServiceUtil.getLayer("website.article_start", "sys.common_audit.apply", paramsMap);
  313. nextService.setRefresh(true); // 需要刷新
  314. setNextService(nextService);
  315. }
  316. }
  317. /**
  318. * 文章修改
  319. *
  320. * @return
  321. * @throws Exception
  322. * @author 陈锋
  323. * @log 2020年9月18日
  324. */
  325. public String modify() throws Exception {
  326. GeneralDBAccess gdba = getGdbaInstance();
  327. AppUser appUser = getAppUser();
  328. Article a2 = getArticleById(gdba, getParameterToLong("articleid"));
  329. if (!Long.valueOf(dataStatusCode.INSERT.getCode()).equals(a2.getDcode())
  330. && !Long.valueOf(dataStatusCode.STAY_SUBMIT.getCode()).equals(a2.getDcode())) {
  331. // setResponsePackage(getResponseErrorMsgPackage());
  332. StringBuilder msgBuilder = new StringBuilder();
  333. msgBuilder.append("[").append(DateTimeUtil.getNowDate()).append("] - 文章修改,ip为:")
  334. .append(getRequest().getLocalAddr()).append(" 篡改的文章 id 为:").append(a2.getArticleid())
  335. .append(",文章标题为:").append(a2.getTitle());
  336. log.error(msgBuilder.toString());
  337. return ERROR_FORWARD;
  338. }
  339. Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
  340. String top = getParameter("top");
  341. String timeSwitch = getParameter("timeSwitch");
  342. String content = getParameterNotXSS("body");
  343. String navIdList = getParameter("navIdList");
  344. Article article = getArticleById(gdba, a2.getArticleid());
  345. PojoUtil.formatRequest(getRequest(), article);
  346. WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
  347. if (wn == null) {
  348. return DEFAULT_FORWARD;
  349. }
  350. if (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", false)) {
  351. return DEFAULT_FORWARD;
  352. }
  353. if (!verifyArticleCopyNavigationList(gdba, navIdList, article, false)) {
  354. return DEFAULT_FORWARD;
  355. }
  356. if (!verifyArticleImageSources(content)) {
  357. return DEFAULT_FORWARD;
  358. }
  359. article.setSticktop("yes".equals(top) ? 1L : 0L);
  360. ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), GsonUtil.toJson(a2));
  361. saveArticleContentFiles(article, content);
  362. article.setLastChangePid(appUser.getUserId());
  363. article.setLastChangeTime(nowTimestamp);
  364. article.setWebsiteid(wn.getWebsiteid());
  365. article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
  366. // 旧的文章是定时发布的,新的文章不是定时发布的,则需要把发布时间设置为空
  367. if (a2.getRelease().equals(1L) && !"yes".equals(timeSwitch)) {
  368. article.setReleaseTime(null);
  369. }
  370. verifyArticleUrl(article, a2, wn);
  371. saveArticleDesc(article, content);
  372. gdba.updateById(article);
  373. saveArticleSortNumber(gdba, article.getArticleid());
  374. saveArticleCopy(gdba, article, appUser, navIdList);
  375. initArticleSticktopSchedule(gdba, article, appUser);
  376. initArticleReleaseTaskSchedule(gdba, article, appUser);
  377. gdba.updateById(article);
  378. setArticleApplyService(article.getArticleid());
  379. gdba.commit();
  380. setResponsePackage(getResponseSuccessMsgPackage());
  381. return DEFAULT_FORWARD;
  382. }
  383. /**
  384. * 根据栏目 id 获取栏目对象
  385. *
  386. * @param gdba
  387. * @param navigationId 栏目 id
  388. * @return
  389. * @throws Exception
  390. * @author 陈锋
  391. * @log 2020年9月26日
  392. */
  393. private WebsiteNavigation getWebsiteNavigationById(GeneralDBAccess gdba, Long navigationId) throws Exception {
  394. return WebsiteTemplateNavUtil.selectNavigationById(gdba, navigationId);
  395. }
  396. private WebsiteNavigation getArticleTargetNavigation(GeneralDBAccess gdba, Long navigationId, String targetName)
  397. throws Exception {
  398. if (navigationId == null || navigationId <= 0) {
  399. setResponsePackage(getResponseWarningMsgPackage("请选择" + targetName));
  400. return null;
  401. }
  402. WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationId);
  403. if (!isArticleTargetNavigation(wn)) {
  404. setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择可发布文章的栏目"));
  405. return null;
  406. }
  407. if (hasEnabledChildNavigation(gdba, navigationId)) {
  408. setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择最下级栏目,请继续向右选择最后一级栏目"));
  409. return null;
  410. }
  411. return wn;
  412. }
  413. private boolean verifyArticleCopyNavigationList(GeneralDBAccess gdba, String navIdList, Article article,
  414. boolean allowLegacyDefaultThumbnail) throws Exception {
  415. if (StringUtil.isNull(navIdList)) {
  416. return true;
  417. }
  418. Set<String> navIdSet = new HashSet<String>();
  419. String[] navIdAry = navIdList.split(",");
  420. for (String navId : navIdAry) {
  421. if (StringUtil.isNull(navId) || navIdSet.contains(navId)) {
  422. continue;
  423. }
  424. navIdSet.add(navId);
  425. WebsiteNavigation wn = getArticleTargetNavigation(gdba, Long.valueOf(navId), "抄送栏目");
  426. if (wn == null) {
  427. return false;
  428. }
  429. if (!verifyNavigationThumbnailRequired(gdba, wn, article, "抄送栏目",
  430. allowLegacyDefaultThumbnail)) {
  431. return false;
  432. }
  433. }
  434. return true;
  435. }
  436. private boolean verifyNavigationThumbnailRequired(GeneralDBAccess gdba, WebsiteNavigation wn, Article article,
  437. String targetName, boolean allowLegacyDefaultThumbnail) throws Exception {
  438. if (wn == null || NAVIGATION_STYLE_TEXT_LIST.equals(wn.getWnlscode())) {
  439. return true;
  440. }
  441. if (article != null && StringUtil.notNull(article.getThumbnail())) {
  442. return true;
  443. }
  444. if (allowLegacyDefaultThumbnail && article != null) {
  445. article.setThumbnail(ARTICLE_DEFAULT_THUMBNAIL);
  446. return true;
  447. }
  448. setResponsePackage(getResponseWarningMsgPackage(targetName + "排版样式不是文字列表时必须上传缩略图"));
  449. return false;
  450. }
  451. private boolean isCollegeRedGraphicListNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception {
  452. if (wn == null || !NAVIGATION_STYLE_GRAPHIC_LIST.equals(wn.getWnlscode())) {
  453. return false;
  454. }
  455. return isCollegeRedTemplateNavigation(gdba, wn);
  456. }
  457. private boolean isCollegeRedTemplateNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception {
  458. Long wtid = wn == null ? null : wn.getWtid();
  459. if (wtid == null && wn != null && wn.getWebsiteid() != null) {
  460. Website website = WebsiteUtil.getWebsiteByID(gdba, wn.getWebsiteid());
  461. wtid = website == null ? null : website.getWtid();
  462. }
  463. if (wtid == null) {
  464. return false;
  465. }
  466. return isCollegeRedTemplateIdCode(gdba, wtid);
  467. }
  468. private boolean isCollegeRedTemplateIdCode(GeneralDBAccess gdba, Long wtid) throws Exception {
  469. String sql = " select id_code from website_template where wtid = :wtid ";
  470. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  471. sqlCmd.setString("wtid", wtid);
  472. Map<String, Object> templateMap = gdba.selectAsMap(sqlCmd);
  473. Object idCode = templateMap == null ? null : templateMap.get("id_code");
  474. return idCode != null && idCode.toString().indexOf(COLLEGE_RED_TEMPLATE_ID_CODE) >= 0;
  475. }
  476. private boolean isArticleTargetNavigation(WebsiteNavigation wn) {
  477. if (wn == null || wn.getWntcode() == null) {
  478. return false;
  479. }
  480. return isArticleTargetWntcode(wn.getWntcode());
  481. }
  482. private boolean isArticleTargetWntcode(Object wntcode) {
  483. if (wntcode == null) {
  484. return false;
  485. }
  486. Long wntcodeLong = Long.valueOf(wntcode.toString());
  487. return Long.valueOf(10010L).equals(wntcodeLong) || Long.valueOf(10060L).equals(wntcodeLong);
  488. }
  489. private boolean hasEnabledChildNavigation(GeneralDBAccess gdba, Long navigationId) throws Exception {
  490. String sql = " select count(*) as c from website_navigation where dcode = 61 and parent_nid = :navigationid ";
  491. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  492. sqlCmd.setString("navigationid", navigationId);
  493. Map<String, Object> resultMap = gdba.selectAsMap(sqlCmd);
  494. return Integer.parseInt(resultMap.get("c").toString()) > 0;
  495. }
  496. /**
  497. * 验证文章的 url 是否需要生成新的、或使用旧的、或使用页面上的
  498. *
  499. * @param newArticle 新文章对象(也就是更新的)
  500. * @param oldArticle 旧文章对象
  501. * @param newArticleNavigation 新文章的的栏目对象
  502. * @throws Exception
  503. * @author 陈锋
  504. * @log 2020年10月11日
  505. */
  506. private void verifyArticleUrl(Article newArticle, Article oldArticle, WebsiteNavigation newArticleNavigation)
  507. throws Exception {
  508. // 新、旧都是一样
  509. if (oldArticle.getAjtcode().equals(newArticle.getAjtcode())) {
  510. // 都是正文、无动作,则使用旧的 url
  511. if (!oldArticle.getAjtcode().equals(10020L)) {// 不是链接
  512. newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
  513. }
  514. // 都是链接时,则使用页面的,使用页面的不用重新设置 url
  515. }
  516. // 旧的是链接,新的不是链接时,则需要生成 url
  517. else if (oldArticle.getAjtcode().equals(10020L) && !newArticle.getAjtcode().equals(10020L)) {
  518. newArticle.setUrl(WebsiteTemplateArticleUtil.getArticleURL(newArticleNavigation));// 生成新的 url
  519. }
  520. // 新的为无动作,则使用旧的
  521. else if (newArticle.getAjtcode().equals(10030L)) {
  522. newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
  523. }
  524. // url 为空时,则用旧的
  525. else if (newArticle.getUrl() == null) {
  526. newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
  527. }
  528. }
  529. /**
  530. * 设置文章变动申请服务
  531. *
  532. * @param articleid 文章 id
  533. * @author 陈锋
  534. * @log 2020年12月8日 下午8:28:18
  535. */
  536. private void setArticleChangeApplyService(Long articleid) {
  537. // 设置下一个服务对象
  538. if (isNextServiceFlag()) {
  539. Map<String, Object> paramsMap = NextServiceUtil.newHashMap();
  540. paramsMap.put("articleid", articleid);
  541. NextService nextService = NextServiceUtil.getLayer("website.article_start_change", "sys.common_audit.change_apply", paramsMap);
  542. nextService.setRefresh(true); // 需要刷新
  543. setNextService(nextService);
  544. }
  545. }
  546. /**
  547. * 文章变动
  548. *
  549. * @return
  550. * @throws Exception
  551. * @author SPACE
  552. * @date 2020年02月09日
  553. */
  554. public String change() throws Exception {
  555. AppUser appUser = getAppUser();
  556. GeneralDBAccess gdba = getGdbaInstance();
  557. Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
  558. String top = getParameter("top");
  559. String timeSwitch = getParameter("timeSwitch");
  560. String content = getParameterNotXSS("body");
  561. String navIdList = getParameter("navIdList");
  562. Article article = getArticleById(gdba, getParameterToLong("articleid"));
  563. boolean legacyThumbnailMissing = StringUtil.isNull(article.getThumbnail());
  564. PojoUtil.formatRequest(getRequest(), article);
  565. WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
  566. if (wn == null) {
  567. return TIPS_FORWARD;
  568. }
  569. if (!verifyNavigationThumbnailRequired(gdba, wn, article, "发布栏目", legacyThumbnailMissing)) {
  570. return TIPS_FORWARD;
  571. }
  572. if (!verifyArticleCopyNavigationList(gdba, navIdList, article, legacyThumbnailMissing)) {
  573. return TIPS_FORWARD;
  574. }
  575. if (!verifyArticleImageSources(content)) {
  576. return TIPS_FORWARD;
  577. }
  578. article.setSticktop("yes".equals(top) ? 1L : 0L);
  579. Article a2 = getArticleById(gdba, article.getArticleid());
  580. ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(),
  581. buildArticleChangeLogContent(a2, nowTimestamp));
  582. verifyArticleUrl(article, a2, wn);
  583. saveArticleContentFiles(article, content);
  584. article.setDcode(dataStatusCode.STAY_SUBMIT.getCode());
  585. article.setLastChangePid(appUser.getUserId());
  586. article.setLastChangeTime(nowTimestamp);
  587. article.setWebsiteid(wn.getWebsiteid());
  588. article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
  589. // 旧的文章设置了定时发布、发布时间,为到指定的发布时间时
  590. if (articleStatusCode.STAY_RELEASE.getCode().equals(a2.getAscode()) && a2.getRelease().equals(1L)
  591. && StringUtil.notNull(a2.getReleaseTaskSchedulesid())) {
  592. // 新的文章没有设置定时发布
  593. if (article.getRelease().equals(0L)) {
  594. article.setReleaseTime(null);
  595. }
  596. }
  597. saveArticleDesc(article, content);
  598. saveArticleCopy(gdba, article, appUser, navIdList);
  599. initArticleSticktopSchedule(gdba, article, appUser);
  600. initArticleReleaseTaskSchedule(gdba, article, appUser);
  601. gdba.updateById(article);
  602. saveArticleSortNumber(gdba, article.getArticleid());
  603. setArticleChangeApplyService(article.getArticleid());
  604. gdba.commit();
  605. setResponsePackage(getResponseSuccessMsgPackage());
  606. return TIPS_FORWARD;
  607. }
  608. private String buildArticleChangeLogContent(Article article, Timestamp snapshotTime) throws Exception {
  609. JsonObject logContent = new JsonParser().parse(GsonUtil.toJson(article)).getAsJsonObject();
  610. if (!isPublishedArticle(article)) {
  611. return logContent.toString();
  612. }
  613. String contentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getContent(), "content",
  614. snapshotTime);
  615. if (StringUtil.notNull(contentSnapshot)) {
  616. logContent.addProperty(PUBLISHED_CONTENT_SNAPSHOT_FIELD, contentSnapshot);
  617. }
  618. String editContentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getEditContent(),
  619. "edit-content", snapshotTime);
  620. if (StringUtil.notNull(editContentSnapshot)) {
  621. logContent.addProperty(PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD, editContentSnapshot);
  622. }
  623. return logContent.toString();
  624. }
  625. private boolean isPublishedArticle(Article article) {
  626. return Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode())
  627. && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode());
  628. }
  629. private String copyPublishedArticleFile(Long articleid, String filePath, String fileType, Timestamp snapshotTime)
  630. throws Exception {
  631. if (StringUtil.isNull(filePath)) {
  632. return null;
  633. }
  634. File source = new File(getWebRootPath() + filePath);
  635. if (!source.exists() || !source.isFile()) {
  636. return null;
  637. }
  638. String snapshotDir = ARTICLE_PUBLISHED_HISTORY_ROOT + articleid + "/";
  639. FileUtil.makeDirectory(new File(getWebRootPath() + snapshotDir));
  640. String fileExt = FileUtil.getFileExt(filePath);
  641. if (StringUtil.isNull(fileExt)) {
  642. fileExt = "html";
  643. } else if (fileExt.startsWith(".")) {
  644. fileExt = fileExt.substring(1);
  645. }
  646. String snapshotPath = snapshotDir + DateTimeUtil.formatDate(snapshotTime, "yyyyMMddHHmmssSSS") + "-"
  647. + fileType + "." + fileExt;
  648. FileUtil.copyFile(source.getAbsolutePath(), getWebRootPath() + snapshotPath);
  649. return snapshotPath;
  650. }
  651. /**
  652. * 删除指定文章的所有抄送记录
  653. *
  654. * @param gdba
  655. * @param article
  656. * @throws Exception
  657. * @author SPACE
  658. * @date 2020年02月09日
  659. */
  660. private void delArticleCopy(GeneralDBAccess gdba, Article article) throws Exception {
  661. String sql = " delete from article_copy where articleid = :articleid ";
  662. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  663. sqlCmd.setString("articleid", article.getArticleid());
  664. gdba.modify(sqlCmd);
  665. }
  666. /**
  667. * 查询指定文章所抄送的栏目列表
  668. *
  669. * @param gdba
  670. * @param article
  671. * @return
  672. * @throws Exception
  673. * @author SPACE
  674. * @date 2020年02月09日
  675. */
  676. private List<Map<String, Object>> getArticleCopyList(GeneralDBAccess gdba, Article article) throws Exception {
  677. String sql = " SELECT wn.navigationid, wn.name, wn.parent_nid, ac.dcode FROM article_copy ac, website_navigation wn where ac.navigationid =" +
  678. " wn.navigationid and ac.articleid = :articleid ";
  679. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  680. sqlCmd.setString("articleid", article.getArticleid());
  681. return gdba.selectAsMapList(sqlCmd);
  682. }
  683. /**
  684. * 获取可以抄送的栏目
  685. *
  686. * @throws Exception
  687. * @author SPACE
  688. * @date 2020年02月09日
  689. */
  690. public void getCopyNavigation() throws Exception {
  691. GeneralDBAccess gdba = getGdbaInstance();
  692. AppUser appUser = getAppUser();
  693. List<Map<String, Object>> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser,
  694. 10010L);
  695. ResponsePackage rp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList));
  696. write(rp.toJsonWriteNonStringValueAsString());
  697. // getWriter().write(FastjsonUtil.toStringJSON(getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList))));
  698. }
  699. /**
  700. * 获取可以发布的栏目
  701. *
  702. * @throws Exception
  703. * @author SPACE
  704. * @date 2020年02月08日
  705. */
  706. public void getIssueNavigation() throws Exception {
  707. GeneralDBAccess gdba = getGdbaInstance();
  708. AppUser appUser = getAppUser();
  709. List<Map<String, Object>> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser,
  710. 10000L);
  711. ResponsePackage rsdp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList));
  712. write(rsdp.toJsonWriteNonStringValueAsString());
  713. }
  714. /**
  715. * 将栏目的名称修改为:上级栏目链/栏目名称
  716. *
  717. * @param gdba
  718. * @param navigationList
  719. * @throws Exception
  720. * @author SPACE
  721. * @date 2020年02月27日
  722. */
  723. void getNavAllParentName(GeneralDBAccess gdba, List<Map<String, Object>> navigationList) throws Exception {
  724. for (Map<String, Object> map : navigationList) {
  725. Object parNid = map.get("parent_nid");
  726. if (StringUtil.isNull(parNid)) {
  727. continue;
  728. }
  729. map.put("name", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString())));
  730. }
  731. }
  732. /**
  733. * 根据栏目ID获取栏目上级链名称
  734. *
  735. * @param gdba 数据库
  736. * @param navID 栏目ID
  737. * @throws Exception
  738. * @author SPACE
  739. * @date 2020年02月27日
  740. */
  741. String getNavAllParentName(GeneralDBAccess gdba, Long navID) throws Exception {
  742. List<WebsiteNavigation> navParentList = WebsiteTemplateNavUtil.getNavParentList(gdba, navID);
  743. if (navParentList.size() == 1) {
  744. return navParentList.get(0).getName();
  745. }
  746. StringBuilder nameBuilder = new StringBuilder();
  747. for (WebsiteNavigation wn : navParentList) {
  748. nameBuilder.append(wn.getName()).append(" / ");
  749. }
  750. return nameBuilder.substring(0, nameBuilder.length() - 2);
  751. }
  752. Map<String, Object> getNavigationMap(GeneralDBAccess gdba, List<Map<String, Object>> navigationList)
  753. throws Exception {
  754. Map<String, Object> retMap = new HashMap<String, Object>();
  755. if (navigationList == null || navigationList.size() == 0) {
  756. retMap.put("data", new ArrayList<Map<String, Object>>());
  757. return retMap;
  758. }
  759. Set<String> websiteSet = new HashSet<String>();
  760. Map<String, List<Map<String, Object>>> websiteNavigationMap = new LinkedHashMap<String, List<Map<String, Object>>>();
  761. for (Map<String, Object> map : navigationList) {
  762. String website = map.get("websiteid").toString();
  763. websiteSet.add(website);
  764. List<Map<String, Object>> websiteNavigationList = websiteNavigationMap.get(website);
  765. if (websiteNavigationList == null) {
  766. websiteNavigationList = new ArrayList<Map<String, Object>>();
  767. websiteNavigationMap.put(website, websiteNavigationList);
  768. }
  769. websiteNavigationList.add(map);
  770. }
  771. if (websiteSet.size() > 1) {
  772. List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
  773. for (String websiteId : websiteNavigationMap.keySet()) {
  774. Website w = new Website();
  775. w.setWebsiteid(Long.valueOf(websiteId));
  776. gdba.selectById(w);
  777. Map<String, Object> map = new HashMap<String, Object>();
  778. map.put("navigationid", "-1");
  779. map.put("name", w.getName());
  780. map.put("children", buildNavigationTree(websiteNavigationMap.get(websiteId)));
  781. dataList.add(map);
  782. }
  783. retMap.put("data", dataList);
  784. } else {
  785. retMap.put("data", buildNavigationTree(navigationList));
  786. }
  787. return retMap;
  788. }
  789. List<Map<String, Object>> buildNavigationTree(List<Map<String, Object>> navigationList) {
  790. Map<String, Map<String, Object>> navigationMap = new LinkedHashMap<String, Map<String, Object>>();
  791. for (Map<String, Object> navigation : navigationList) {
  792. Map<String, Object> item = new HashMap<String, Object>(navigation);
  793. item.remove("children");
  794. navigationMap.put(item.get("navigationid").toString(), item);
  795. }
  796. List<Map<String, Object>> rootList = new ArrayList<Map<String, Object>>();
  797. for (Map<String, Object> navigation : navigationMap.values()) {
  798. Object parentNid = navigation.get("parent_nid");
  799. Map<String, Object> parent = parentNid == null ? null : navigationMap.get(parentNid.toString());
  800. if (parent == null) {
  801. rootList.add(navigation);
  802. continue;
  803. }
  804. @SuppressWarnings("unchecked")
  805. List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
  806. if (children == null) {
  807. children = new ArrayList<Map<String, Object>>();
  808. parent.put("children", children);
  809. }
  810. children.add(navigation);
  811. }
  812. setDisabledNavigationList(rootList);
  813. return rootList;
  814. }
  815. private void setDisabledNavigationList(List<Map<String, Object>> navigationList) {
  816. for (Map<String, Object> navigation : navigationList) {
  817. @SuppressWarnings("unchecked")
  818. List<Map<String, Object>> children = (List<Map<String, Object>>) navigation.get("children");
  819. if (children != null && children.size() > 0) {
  820. setDisabledNavigationList(children);
  821. continue;
  822. }
  823. if (!isArticleTargetWntcode(navigation.get("wntcode"))) {
  824. navigation.put("disabled", true);
  825. }
  826. }
  827. }
  828. private List<Map<String, Object>> getArticleFlowList(GeneralDBAccess gdba, Long articleid) throws Exception {
  829. String sql = " select ap.applyid, ap.ascode, "
  830. + " coalesce(asc1.name, '未知状态') as statusName, "
  831. + " coalesce(initp.name, '未知') as initiatorName, "
  832. + " coalesce((select group_concat(distinct cp.name order by cp.name separator '、') "
  833. + " from audit cau join person cp on cp.personid = cau.personid "
  834. + " where ap.ascode = 11 and cau.applyid = ap.applyid and cau.dcode = 31 "
  835. + " and cau.audit_time is null and cau.acode in (51, 101)), '') as currentAuditors, "
  836. + " case "
  837. + " when lower(ap.flow_key) like '%articlechange%' then '变动审核' "
  838. + " when lower(ap.flow_key) like '%articledisable%' then '停用审核' "
  839. + " when lower(ap.flow_key) like '%articleenable%' then '启用审核' "
  840. + " when lower(ap.flow_key) like '%articlerelease%' then '发布审核' "
  841. + " else '文章审核' "
  842. + " end as flowName, "
  843. + " case "
  844. + " when ap.ascode = 11 then 'warning' "
  845. + " when ap.ascode in (41, 51) then 'success' "
  846. + " when ap.ascode in (21, 31, 61) then 'danger' "
  847. + " else 'info' "
  848. + " end as statusType, "
  849. + " date_format(ap.create_time, '%Y-%m-%d %H:%i:%s') as createTime, "
  850. + " ifnull(date_format(ap.end_time, '%Y-%m-%d %H:%i:%s'), '') as endTime, "
  851. + " ifnull((select au.auditid from audit au "
  852. + " where au.applyid = ap.applyid and au.dcode <> 72 "
  853. + " order by case "
  854. + " when ap.ascode = 11 and au.dcode = 31 and au.audit_time is null and au.acode in (51, 101) then 0 "
  855. + " when au.audit_time is not null then 1 "
  856. + " else 2 end, "
  857. + " ifnull(au.steps, 0) desc, au.auditid desc limit 1), 0) as auditid "
  858. + " from apply ap "
  859. + " left join apply_status_code asc1 on asc1.apply_status_code = ap.ascode "
  860. + " left join person initp on initp.personid = ap.personid "
  861. + " where ap.dcode <> 72 and ap.table_name = 'article' and ap.table_key = 'articleid' "
  862. + " and ap.table_key_value = :articleid "
  863. + " order by case when ap.ascode = 11 then 0 else 1 end, ap.create_time desc, ap.applyid desc ";
  864. SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
  865. sqlCmd.setString("articleid", articleid);
  866. return gdba.selectAsMapList(sqlCmd);
  867. }
  868. /**
  869. * 文章信息
  870. *
  871. * @return
  872. * @throws Exception
  873. * @author SPACE
  874. * @date 2020年02月09日
  875. */
  876. public String info() throws Exception {
  877. Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class);
  878. GeneralDBAccess gdba = getGdbaInstance();
  879. gdba.selectById(article);
  880. List<Map<String, Object>> articleCopyList = getArticleCopyList(gdba, article);
  881. getNavAllParentName(gdba, articleCopyList);
  882. String navAllName = getNavAllParentName(gdba, article.getNavigationid());
  883. Website website = new Website();
  884. website.setWebsiteid(article.getWebsiteid());
  885. gdba.selectById(website);
  886. if (!articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode())
  887. || (articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode())
  888. && article.getUrl().startsWith("/"))) {
  889. // 设置查看文章时的 url
  890. String url = appendWebsiteDomain(website.getPort().toString(), website.getDomains(), website.getProtocol(),
  891. article.getUrl());
  892. article.setUrl(url);
  893. }
  894. boolean isShowModifyReleaseTime = false;// 是否显示修改发布时间,默认不显示
  895. // 变动时的发布时间,在用状态、已发布
  896. if (Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode())
  897. && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) {
  898. isShowModifyReleaseTime = true;
  899. }
  900. // 修改时的发布时间,录入状态、待发布、不是定时发布
  901. if (Long.valueOf(dataStatusCode.INSERT.getCode()).equals(article.getDcode()) && article.getRelease() == 0L) {
  902. isShowModifyReleaseTime = true;
  903. }
  904. boolean isShowpreview = false;// 是否显示预览,默认不显示
  905. // 文章数据状态为 在用,文章状态 已发布
  906. if (article.getDcode().equals(Long.valueOf(dataStatusCode.USE.getCode()))
  907. && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) {
  908. // 文章动作 跳转正文页 或 自定义链接
  909. if (article.getAjtcode().equals(articleJumpTypeCode.MAIN_BODY.getCode())
  910. || article.getAjtcode().equals(articleJumpTypeCode.CUSTOM_LINK.getCode())) {
  911. isShowpreview = true;
  912. }
  913. }
  914. setRequestAttribute("isShowpreview", isShowpreview);// 是否显示预览
  915. setRequestAttribute("isShowModifyReleaseTime", isShowModifyReleaseTime);// 是否显示修改发布时间
  916. setRequestAttribute("article", article);
  917. setRequestAttribute("sortNumber", getArticleSortNumber(gdba, article.getArticleid()));
  918. setRequestAttribute("navAllName", navAllName);
  919. setRequestAttribute("copyNav", GsonUtil.toJson(articleCopyList));
  920. setRequestAttribute("articleFlowList", GsonUtil.toJson(getArticleFlowList(gdba, article.getArticleid())));
  921. WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid());
  922. String articleContentForPreview;
  923. try {
  924. articleContentForPreview = FileUtil.readFile(getWebRootPath() + article.getContent());
  925. setRequestAttribute("body", articleContentForPreview);
  926. } catch (Exception e) {
  927. articleContentForPreview = "内容文件不存在或已被删除";
  928. setRequestAttribute("body", articleContentForPreview);
  929. }
  930. setRequestAttribute("infoPreviewHtmlB64", Base64.getEncoder().encodeToString(
  931. buildArticleInfoPreviewHtml(article, website, navigation, articleContentForPreview)
  932. .getBytes(StandardCharsets.UTF_8)));
  933. try {
  934. setRequestAttribute("editBody", FileUtil.readFile(getWebRootPath() + article.getEditContent()));
  935. } catch (Exception e) {
  936. setRequestAttribute("editBody", "内容文件不存在或已被删除");
  937. }
  938. ArticleJumpTypeCode ajtCode = new ArticleJumpTypeCode();
  939. ajtCode.setAjtcode(article.getAjtcode());
  940. gdba.selectById(ajtCode);
  941. setRequestAttribute("ajtCode", ajtCode);// 查看文章时用到
  942. return DEFAULT_FORWARD;
  943. }
  944. /**
  945. * 拼接网站域名
  946. *
  947. * @param port 端口
  948. * @param domains 域名
  949. * @param protocol 协议
  950. * @param catalogURI 目录
  951. * @return 带有协议和端口的网站域名
  952. * @author SPACE
  953. * @log Oct 9, 2020 11:16:33 PM
  954. */
  955. private static String appendWebsiteDomain(String port, String domains, String protocol, String catalogURI) {
  956. String href = null;
  957. String[] domainsAry = domains.split(";");
  958. if (domainsAry.length > 0) {
  959. port = "80".equals(port) ? "" : (":" + port); // 非 80 端口进行特殊处理
  960. if (domainsAry[0].endsWith("/")) {
  961. domainsAry[0] = domainsAry[0].substring(0, domainsAry[0].lastIndexOf("/"));
  962. }
  963. href = protocol + "://" + domainsAry[0] + port + catalogURI;
  964. }
  965. // 未找到域名
  966. else {
  967. href = "javascript:alert('website domain is null!');";
  968. }
  969. return href;
  970. }
  971. /**
  972. * 文章置顶周期
  973. *
  974. * @param article
  975. * @throws Exception
  976. * @author SPACE
  977. * @date 2020年02月09日
  978. */
  979. private void initArticleSticktopSchedule(GeneralDBAccess gdba, Article article, AppUser appUser)
  980. throws ParseException, Exception {
  981. // 删除掉已经添加了的定时任务
  982. if (StringUtil.notNull(article.getSticktopSchedulesid())) {
  983. ScheduleImpl.delSchedule(article.getSticktopSchedulesid(), gdba);
  984. }
  985. // 不置顶
  986. if (article.getSticktop() == 0) {
  987. article.setSticktopEndTime(null);
  988. return;
  989. }
  990. // 非在用状态
  991. if (!article.getDcode().equals(61L)) {
  992. return;
  993. }
  994. Map<String, Object> data = new HashMap<String, Object>();
  995. data.put("articleid", article.getArticleid());
  996. Long scheduleid = ScheduleImpl.addSchedule(
  997. "文章“" + article.getArticleid() + "/" + article.getTitle() + "”置顶周期任务",
  998. DateTimeUtil.formatDateYMdHms(article.getSticktopEndTime()),
  999. "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleSticktop", appUser.getUserId(),
  1000. data, gdba);
  1001. article.setSticktopSchedulesid(scheduleid);
  1002. }
  1003. /**
  1004. * 文章定时发布任务
  1005. *
  1006. * @param gdba
  1007. * @param article
  1008. * @param appUser
  1009. * @throws Exception
  1010. * @author 陈锋
  1011. * @log 2020年9月16日
  1012. */
  1013. private void initArticleReleaseTaskSchedule(GeneralDBAccess gdba, Article article, AppUser appUser)
  1014. throws Exception {
  1015. // 删掉已经添加的定时发布文章任务
  1016. if (StringUtil.notNull(article.getReleaseTaskSchedulesid())) {
  1017. ScheduleImpl.delSchedule(article.getReleaseTaskSchedulesid(), gdba);
  1018. article.setReleaseTaskSchedulesid(null);
  1019. }
  1020. if (article.getRelease() == 0) {
  1021. // article.setReleaseTime(null);
  1022. return;
  1023. }
  1024. article.setAscode(articleStatusCode.STAY_RELEASE.getCode());
  1025. Map<String, Object> data = new HashMap<String, Object>();
  1026. data.put("articleid", article.getArticleid());
  1027. Long scheduleid = ScheduleImpl.addSchedule(
  1028. "文章“" + article.getArticleid() + "/" + article.getTitle() + "”定时发布任务",
  1029. DateTimeUtil.formatDateYMdHms(article.getReleaseTime()),
  1030. "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleRelease", appUser.getUserId(), data,
  1031. gdba);
  1032. article.setReleaseTaskSchedulesid(scheduleid);
  1033. }
  1034. /**
  1035. * 文章列表
  1036. *
  1037. * @return
  1038. * @throws Exception
  1039. * @author SPACE
  1040. * @date 2020年02月09日
  1041. */
  1042. public String list() throws Exception {
  1043. AppUser appUser = getAppUser();
  1044. StringBuilder sqlBuilder = new StringBuilder(" Select ");
  1045. sqlBuilder.append(
  1046. " a.articleid, a.dcode, a.thumbnail, (Select name from data_status_code dsc where dsc.dcode = a.dcode) as 'dsname', a.ascode, a" +
  1047. ".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" +
  1048. ".create_time, '%Y-%m-%d') as 'ctime', concat(per.name, ' / ', dep.name) pname_dname ");
  1049. sqlBuilder.append(
  1050. " ,(Select name from website_navigation wn where wn.navigationid = a.navigationid ) as 'navname'");
  1051. sqlBuilder.append(
  1052. " ,(Select name from website w where w.websiteid = a.websiteid ) as 'website_name', dep.departmentid ");
  1053. sqlBuilder.append(" from article a ");
  1054. sqlBuilder.append(" left join person per on a.create_pid = per.personid ");
  1055. sqlBuilder.append(" left join department dep on per.departmentid = dep.departmentid ");
  1056. sqlBuilder.append(
  1057. " where a.unitid = :unitid and if((a.dcode in (11, 21)), (a.create_pid = :createPid), (a.create_pid > 0)) ");
  1058. sqlBuilder.append(" and a.dcode != 72 "); // 过滤已删除的数据
  1059. SqlCommandImpl sqlCmd = new SqlCommandImpl();
  1060. sqlCmd.setString("unitid", appUser.getUnitId()).setString("createPid", appUser.getUserId());
  1061. GdbaQueryUtil.appendLikeSql(sqlBuilder, sqlCmd, "title", getParameter("title")); // 标题
  1062. GdbaQueryUtil.appendFieldSql(sqlBuilder, sqlCmd, "a.dcode", getParameter("dcode")); // 数据状态码
  1063. // 栏目
  1064. String navigation = getParameter("navigation");
  1065. if (StringUtil.notNull(navigation)) {
  1066. sqlBuilder.append("and (" + GdbaQueryUtil.getInSql(sqlCmd, "navigationid", navigation, ",")
  1067. + "or articleid in (Select ac.articleid from website_navigation wn, article_copy ac, article a "
  1068. + "where wn.navigationid = ac.navigationid and a.articleid = ac.articleid and ac.dcode = 61 and a.dcode = 61 "
  1069. + "and wn.dcode = 61 and " + GdbaQueryUtil.getInSql(sqlCmd, "ac.navigationid", navigation, ",")
  1070. + " ))");
  1071. }
  1072. // 我发布的
  1073. String issue = getParameter("issue");
  1074. if (StringUtil.notNull(issue) && ConstVars.TRUE.equals(issue)) {
  1075. sqlBuilder.append(" and a.create_pid = :cpid ");
  1076. sqlCmd.setString("cpid", appUser.getUserId());
  1077. }
  1078. /* 年月日 */
  1079. String dateTime = getParameter("dateTime");
  1080. if (StringUtil.notNull(dateTime)) {
  1081. String[] dateTimeAry = dateTime.split(",");
  1082. sqlBuilder.append(
  1083. " and date_format(release_time, '%Y-%m-%d') >= date_format(:startTime, '%Y-%m-%d') and date_format(release_time, '%Y-%m-%d') <=" +
  1084. " date_format(:endTime, '%Y-%m-%d') ");
  1085. sqlCmd.setString("startTime", dateTimeAry[0]).setString("endTime", dateTimeAry[1]);
  1086. }
  1087. GeneralDBAccess gdba = getGdbaInstance();
  1088. // 获取可管理的网站
  1089. List<Map<String, Object>> manageWebsiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(gdba,
  1090. getAppUser());
  1091. if (manageWebsiteList.size() > 0) {
  1092. sqlBuilder.append(" and ( ").append(GdbaQueryUtil.getInSql(sqlCmd, "a.websiteid",
  1093. AppWebsiteManageUtil.websiteListIDToAry(manageWebsiteList)));
  1094. sqlBuilder.append("or (a.create_pid = :cpid2 )) ");
  1095. } else {
  1096. sqlBuilder.append(" and (a.create_pid = :cpid2 ) ");
  1097. }
  1098. sqlCmd.setString("cpid2", appUser.getUserId());
  1099. // 排序方式
  1100. String sort = getParameter("sort");
  1101. if (StringUtil.isNull(sort) || "sort_new".equals(sort)) {
  1102. sqlBuilder.append(" order by dcode asc, ").append(SortOrderUtil.articleSort("a"));
  1103. } else if ("sort_top".equals(sort)) {
  1104. sqlBuilder.append(" order by dcode asc, ")
  1105. .append(SortOrderUtil.validSortRank("a.sort_number")).append(", ")
  1106. .append("case when ").append(SortOrderUtil.validSortCondition("a.sort_number"))
  1107. .append(" then a.sort_number else null end asc, read_count desc, release_time desc, articleid desc ");
  1108. } else if ("sort_bottom".equals(sort)) {
  1109. sqlBuilder.append(" order by dcode asc, ")
  1110. .append(SortOrderUtil.validSortRank("a.sort_number")).append(", ")
  1111. .append("case when ").append(SortOrderUtil.validSortCondition("a.sort_number"))
  1112. .append(" then a.sort_number else null end asc, read_count asc, release_time desc, articleid desc ");
  1113. }
  1114. sqlCmd.setExecuteSql(sqlBuilder.toString());
  1115. List<Map<String, Object>> articleList = gdba.selectAsMapList(sqlCmd, getAppsPageBean());
  1116. for (Map<String, Object> map : articleList) {
  1117. // 校验是否拥有该网站的管理权限
  1118. for (Map<String, Object> websiteMap : manageWebsiteList) {
  1119. if (map.get("websiteid").toString().equals(websiteMap.get("websiteid").toString())) {
  1120. map.put("isManagerDepartmentArticleFlag", "true");
  1121. break;
  1122. }
  1123. }
  1124. map.put("navAllName", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString())));
  1125. }
  1126. ResponsePackage rsp = getResponseSuccessPackage();
  1127. rsp.setRequestAttribute("articleList", articleList);
  1128. setResponsePackage(rsp);
  1129. return DEFAULT_FORWARD;
  1130. }
  1131. /**
  1132. * 保存文章抄送
  1133. *
  1134. * @param gdba
  1135. * @param article
  1136. * @param appUser
  1137. * @param navIdList
  1138. * @throws Exception
  1139. * @author SPACE
  1140. * @date 2020年02月09日
  1141. */
  1142. private void saveArticleCopy(GeneralDBAccess gdba, Article article, AppUser appUser, String navIdList)
  1143. throws Exception {
  1144. delArticleCopy(gdba, article);
  1145. if (StringUtil.isNull(navIdList)) {
  1146. return;
  1147. }
  1148. Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
  1149. String[] navIdAry = navIdList.split(",");
  1150. Set<String> navIdSet = new HashSet<String>();
  1151. for (String navId : navIdAry) {
  1152. if (navIdSet.contains(navId)) {
  1153. continue;
  1154. }
  1155. navIdSet.add(navId);
  1156. ArticleCopy ac = new ArticleCopy();
  1157. ac.setArticleid(article.getArticleid());
  1158. ac.setNavigationid(Long.valueOf(navId));
  1159. ac.setCreatePid(appUser.getUserId());
  1160. ac.setCreateTime(nowTimestamp);
  1161. ac.setDcode(dataStatusCode.INSERT_AUDIT.getCode());
  1162. gdba.insertByBean(ac);
  1163. }
  1164. }
  1165. /**
  1166. * 文章录入前置服务
  1167. *
  1168. * @return
  1169. * @throws Exception
  1170. * @author SPACE
  1171. * @log Oct 14, 2020 10:32:06 PM
  1172. */
  1173. public String articleAddBefore() throws Exception {
  1174. List<Map<String, Object>> websiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(getGdbaInstance(),
  1175. getAppUser());
  1176. // 默认找可管理的第一个网站
  1177. if (websiteList != null && websiteList.size() > 0) {
  1178. setRequestAttribute("article_sources", websiteList.get(0).get("name"));
  1179. }
  1180. return DEFAULT_FORWARD;
  1181. }
  1182. /**
  1183. * 生成文章正文临时预览。
  1184. *
  1185. * @throws Exception
  1186. * @author SPACE
  1187. */
  1188. public void preview() throws Exception {
  1189. String content = getParameterNotXSS("body");
  1190. String title = getParameterNotXSS("title");
  1191. String source = getParameterNotXSS("source");
  1192. String desc = getParameterNotXSS("desc");
  1193. Long navigationid = getParameterToLong("navigationid");
  1194. if (StringUtil.isNull(content)) {
  1195. write(getResponseWarningMsgPackage("正文内容为空").toJson());
  1196. return;
  1197. }
  1198. if (navigationid == null || navigationid <= 0) {
  1199. write(getResponseWarningMsgPackage("请先选择发布栏目").toJson());
  1200. return;
  1201. }
  1202. GeneralDBAccess gdba = getGdbaInstance();
  1203. WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationid);
  1204. if (!isArticleTargetNavigation(wn)) {
  1205. write(getResponseWarningMsgPackage("发布栏目必须选择可发布文章的栏目").toJson());
  1206. return;
  1207. }
  1208. if (hasEnabledChildNavigation(gdba, navigationid)) {
  1209. write(getResponseWarningMsgPackage("发布栏目必须选择最下级栏目,请继续向右选择最后一级栏目").toJson());
  1210. return;
  1211. }
  1212. String editPath = WebEditorUtil.createHtmlFile(content);
  1213. String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath,
  1214. space.apps.moudules.website.common.ConstVars.domain);
  1215. String runPath = WebEditorUtil.createHtmlFile(runContent);
  1216. String previewKey = java.util.UUID.randomUUID().toString().replace("-", "");
  1217. setSessionAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + previewKey,
  1218. buildPreviewInfo(runPath, wn, title, source, desc));
  1219. Map<String, Object> retMap = new HashMap<String, Object>();
  1220. retMap.put("url", "/apps?ark=website.article_preview_view&key=" + URLEncoder.encode(previewKey, "UTF-8"));
  1221. write(getResponseSuccessDataPackage(retMap).toJsonWriteNonStringValueAsString());
  1222. }
  1223. /**
  1224. * 输出文章正文临时预览内容。
  1225. *
  1226. * @throws Exception
  1227. * @author SPACE
  1228. */
  1229. public void previewView() throws Exception {
  1230. getResponse().setContentType("text/html;charset=UTF-8");
  1231. String key = getParameter("key");
  1232. if (StringUtil.isNull(key)) {
  1233. writePreviewUnavailable();
  1234. return;
  1235. }
  1236. Object previewObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key);
  1237. String previewPath = getPreviewRunPath(previewObj);
  1238. File previewFile = getSafePreviewFile(previewPath);
  1239. if (previewFile == null) {
  1240. writePreviewUnavailable();
  1241. return;
  1242. }
  1243. if (previewObj instanceof Map) {
  1244. renderArticlePreviewPage(previewObj, previewFile);
  1245. return;
  1246. }
  1247. write(buildArticlePreviewHtml(null, null, FileUtil.readFile(previewFile.getPath())));
  1248. }
  1249. /**
  1250. * 文章信息弹窗内容区 PC 预览(与三端预览 PC 端同源)。
  1251. */
  1252. public void infoPreviewView() throws Exception {
  1253. getResponse().setContentType("text/html;charset=UTF-8");
  1254. Long articleid = getParameterToLong("articleid");
  1255. if (articleid == null || articleid <= 0) {
  1256. writePreviewUnavailable();
  1257. return;
  1258. }
  1259. GeneralDBAccess gdba = getGdbaInstance();
  1260. Article article = new Article();
  1261. article.setArticleid(articleid);
  1262. gdba.selectById(article);
  1263. Website website = new Website();
  1264. website.setWebsiteid(article.getWebsiteid());
  1265. gdba.selectById(website);
  1266. WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid());
  1267. String articleContent;
  1268. try {
  1269. articleContent = FileUtil.readFile(getWebRootPath() + article.getContent());
  1270. } catch (Exception e) {
  1271. writePreviewUnavailable();
  1272. return;
  1273. }
  1274. write(buildArticleInfoPreviewHtml(article, website, navigation, articleContent));
  1275. }
  1276. private String buildArticleInfoPreviewHtml(Article article, Website website, WebsiteNavigation navigation,
  1277. String articleContent) {
  1278. Map<String, Object> previewInfo = new HashMap<String, Object>();
  1279. previewInfo.put(PREVIEW_TITLE_KEY, article.getTitle());
  1280. previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(article.getSource(), website.getName()));
  1281. previewInfo.put(PREVIEW_RELEASE_TIME_KEY, formatArticleReleaseTime(article.getReleaseTime()));
  1282. previewInfo.put(PREVIEW_NAVIGATION_ID_KEY,
  1283. article.getNavigationid() == null ? "" : article.getNavigationid().toString());
  1284. previewInfo.put(PREVIEW_WEBSITE_ID_KEY,
  1285. article.getWebsiteid() == null ? "" : article.getWebsiteid().toString());
  1286. return buildArticlePreviewHtml(previewInfo, navigation, website, articleContent);
  1287. }
  1288. private String formatArticleReleaseTime(Timestamp releaseTime) {
  1289. if (releaseTime == null) {
  1290. return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm");
  1291. }
  1292. try {
  1293. String formatted = DateTimeUtil.formatDateYMdHms(releaseTime);
  1294. return StringUtil.isNull(formatted) ? DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm") : formatted;
  1295. } catch (ParseException e) {
  1296. return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm");
  1297. }
  1298. }
  1299. private Map<String, Object> buildPreviewInfo(String runPath, WebsiteNavigation navigation, String title,
  1300. String source, String desc) {
  1301. Map<String, Object> previewInfo = new HashMap<String, Object>();
  1302. previewInfo.put(PREVIEW_RUN_PATH_KEY, runPath);
  1303. previewInfo.put(PREVIEW_TITLE_KEY, firstNotBlank(title, "正文预览"));
  1304. previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(source, ""));
  1305. previewInfo.put(PREVIEW_DESC_KEY, firstNotBlank(desc, ""));
  1306. previewInfo.put(PREVIEW_NAVIGATION_ID_KEY,
  1307. navigation == null || navigation.getNavigationid() == null ? "" : navigation.getNavigationid().toString());
  1308. previewInfo.put(PREVIEW_WEBSITE_ID_KEY,
  1309. navigation == null || navigation.getWebsiteid() == null ? "" : navigation.getWebsiteid().toString());
  1310. return previewInfo;
  1311. }
  1312. @SuppressWarnings("rawtypes")
  1313. private String getPreviewRunPath(Object previewObj) {
  1314. if (previewObj instanceof Map) {
  1315. Object runPath = ((Map) previewObj).get(PREVIEW_RUN_PATH_KEY);
  1316. return runPath == null ? "" : runPath.toString();
  1317. }
  1318. return previewObj == null ? "" : previewObj.toString();
  1319. }
  1320. @SuppressWarnings("rawtypes")
  1321. private void renderArticlePreviewPage(Object previewObj, File previewFile) throws Exception {
  1322. Map previewInfo = (Map) previewObj;
  1323. GeneralDBAccess gdba = getGdbaInstance();
  1324. Long navigationId = parseLong(previewInfo.get(PREVIEW_NAVIGATION_ID_KEY));
  1325. Long websiteId = parseLong(previewInfo.get(PREVIEW_WEBSITE_ID_KEY));
  1326. WebsiteNavigation navigation = navigationId == null ? null : getWebsiteNavigationById(gdba, navigationId);
  1327. if (navigation != null && navigation.getWebsiteid() != null) {
  1328. websiteId = navigation.getWebsiteid();
  1329. }
  1330. Website website = websiteId == null ? null : WebsiteUtil.getWebsiteByID(gdba, websiteId);
  1331. String articleContent = restorePreviewLazyImages(FileUtil.readFile(previewFile.getPath()));
  1332. write(buildArticlePreviewHtml(previewInfo, navigation, website, articleContent));
  1333. }
  1334. private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, Website website,
  1335. String articleContent) {
  1336. String title = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_TITLE_KEY), "正文预览");
  1337. String source = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_SOURCE_KEY),
  1338. website == null ? "" : website.getName());
  1339. String releaseTime = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_RELEASE_TIME_KEY),
  1340. DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm"));
  1341. String content = restorePreviewLazyImages(firstNotBlank(articleContent, ""));
  1342. StringBuilder html = new StringBuilder();
  1343. html.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">")
  1344. .append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">")
  1345. .append("<link rel=\"stylesheet\" href=\"/main/ffkj-portal/portal-source.css?v=20260703-article-image-fit-v2\">")
  1346. .append("<link rel=\"stylesheet\" href=\"/apps/space/css/space.editor.css?v=20260703-article-image-fit-v2\">")
  1347. .append("<style>")
  1348. .append("html{height:100%;overflow:hidden;}")
  1349. .append("body{margin:0;height:100%;overflow-x:hidden;overflow-y:auto;background:#f5f7fa;color:#1f2937;font-family:Arial,'Microsoft YaHei',sans-serif;}")
  1350. .append(".preview-article{box-sizing:border-box;max-width:900px;margin:0 auto;padding:36px 32px;background:#fff;min-height:100%;}")
  1351. .append(".preview-article.article-panel{padding:36px 32px!important;}")
  1352. .append(".preview-article-header{margin:0 0 22px;padding:0 0 18px;border-bottom:3px solid #a40011;}")
  1353. .append(".preview-article-title{margin:0;color:#a40011;font-size:30px;line-height:1.35;font-weight:700;letter-spacing:0;}")
  1354. .append(".preview-article-meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:14px;color:#666;font-size:14px;line-height:1.5;}")
  1355. .append(".preview-article-body{font-size:16px;line-height:1.9;color:#333;}")
  1356. .append(".preview-article-body .ck-content,#jquery-lazyload-container.ck-content{width:100%!important;margin:0!important;padding:0!important;}")
  1357. .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;}")
  1358. .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;}")
  1359. .append(".preview-article-body p:has(img),.preview-article-body div:has(img),.preview-article-body figure:has(img),")
  1360. .append(".article-body p:has(img),.article-body div:has(img),.article-body figure:has(img),")
  1361. .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;}")
  1362. .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;}")
  1363. .append(".preview-article-body figure.space-editor-pdf-viewer{max-width:100%;}")
  1364. .append(".preview-article-body iframe.space-editor-pdf-frame{width:100%;height:min(78vh,720px);min-height:480px;}")
  1365. .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;}}")
  1366. .append("</style></head><body>")
  1367. .append("<article class=\"preview-article article-panel school-article-panel\">")
  1368. .append("<header class=\"preview-article-header article-header\">");
  1369. html.append("<h1 class=\"preview-article-title\">").append(escapeHtml(title)).append("</h1>")
  1370. .append("<div class=\"preview-article-meta\">")
  1371. .append("<span>").append(escapeHtml(releaseTime)).append("</span>");
  1372. if (!StringUtil.isNull(source)) {
  1373. html.append("<span>来源:").append(escapeHtml(source)).append("</span>");
  1374. }
  1375. html.append("</div></header>")
  1376. .append("<div class=\"preview-article-body article-body\" data-article-preview=\"true\">")
  1377. .append(content)
  1378. .append("</div></article>")
  1379. .append("<script src=\"/apps/space/js/secure-pdf.js?v=20260709-pdf-secure\"></script>")
  1380. .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>")
  1381. .append("</body></html>");
  1382. return html.toString();
  1383. }
  1384. private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, String articleContent) {
  1385. return buildArticlePreviewHtml(previewInfo, navigation, null, articleContent);
  1386. }
  1387. private String restorePreviewLazyImages(String articleContent) {
  1388. if (StringUtil.isNull(articleContent)) {
  1389. return articleContent;
  1390. }
  1391. Document doc = Jsoup.parseBodyFragment(normalizeLocalUploadResourceUrl(articleContent));
  1392. Elements lazyImages = doc.select("img[data-original]");
  1393. for (Element image : lazyImages) {
  1394. if (StringUtil.isNull(image.attr("src"))) {
  1395. image.attr("src", image.attr("data-original"));
  1396. }
  1397. }
  1398. normalizePreviewArticleImages(doc);
  1399. doc.select("script").remove();
  1400. unwrapArticleContentContainer(doc);
  1401. return doc.body().html();
  1402. }
  1403. private void unwrapArticleContentContainer(Document doc) {
  1404. Elements wrappers = doc.select("#jquery-lazyload-container, div.ck-content");
  1405. for (Element wrapper : wrappers) {
  1406. wrapper.unwrap();
  1407. }
  1408. }
  1409. private void normalizePreviewArticleImages(Document doc) {
  1410. Elements figures = doc.select("figure.image, figure.image_resized, figure:has(img), .ck-content .image");
  1411. for (Element figure : figures) {
  1412. figure.removeAttr("width");
  1413. figure.removeAttr("height");
  1414. figure.attr("style", "display:block;width:100%;max-width:100%;margin:18px 0;text-align:left;");
  1415. }
  1416. Elements images = doc.select("img");
  1417. for (Element image : images) {
  1418. image.removeAttr("width");
  1419. image.removeAttr("height");
  1420. image.removeAttr("hspace");
  1421. image.removeAttr("vspace");
  1422. image.removeAttr("border");
  1423. image.attr("style", "display:block;width:100%;max-width:100%;height:auto;margin:18px 0;box-sizing:border-box;");
  1424. }
  1425. Elements mediaBlocks = doc.select("p:has(img), div:has(img), figure:has(img)");
  1426. for (Element block : mediaBlocks) {
  1427. String style = block.attr("style");
  1428. style = stripArticleImageStyleProperty(style, "width");
  1429. style = stripArticleImageStyleProperty(style, "max-width");
  1430. style = stripArticleImageStyleProperty(style, "margin");
  1431. style = stripArticleImageStyleProperty(style, "text-align");
  1432. style = stripArticleImageStyleProperty(style, "text-indent");
  1433. block.attr("style", joinArticleImageStyle(style,
  1434. "text-align:left;text-indent:0;"));
  1435. }
  1436. }
  1437. private String stripArticleImageStyleProperty(String style, String property) {
  1438. if (StringUtil.isNull(style) || StringUtil.isNull(property)) {
  1439. return style == null ? "" : style;
  1440. }
  1441. return style.replaceAll("(?i)" + Pattern.quote(property) + "\\s*:[^;\"']*(;|$)", "$1").trim();
  1442. }
  1443. private String joinArticleImageStyle(String baseStyle, String appendStyle) {
  1444. String normalizedBase = baseStyle == null ? "" : baseStyle.trim();
  1445. if (normalizedBase.length() > 0 && !normalizedBase.endsWith(";")) {
  1446. normalizedBase += ";";
  1447. }
  1448. return normalizedBase + appendStyle;
  1449. }
  1450. private String normalizeLocalUploadResourceUrl(String content) {
  1451. if (StringUtil.isNull(content) || content.indexOf("/web/upload/") < 0) {
  1452. return content;
  1453. }
  1454. return LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN.matcher(content).replaceAll("$1");
  1455. }
  1456. private String escapeHtml(String value) {
  1457. if (value == null) {
  1458. return "";
  1459. }
  1460. return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
  1461. .replace("\"", "&quot;").replace("'", "&#39;");
  1462. }
  1463. private Long parseLong(Object value) {
  1464. if (value == null || StringUtil.isNull(value.toString())) {
  1465. return null;
  1466. }
  1467. try {
  1468. return Long.valueOf(value.toString());
  1469. } catch (Exception e) {
  1470. return null;
  1471. }
  1472. }
  1473. private String firstNotBlank(Object value, String fallback) {
  1474. if (value == null) {
  1475. return fallback;
  1476. }
  1477. String text = value.toString().trim();
  1478. return text.length() == 0 ? fallback : text;
  1479. }
  1480. private File getSafePreviewFile(String previewPath) throws Exception {
  1481. if (StringUtil.isNull(previewPath)) {
  1482. return null;
  1483. }
  1484. String normalizedPath = previewPath.replace("\\", "/");
  1485. if (!normalizedPath.endsWith(".html")) {
  1486. return null;
  1487. }
  1488. File webRoot = new File(getWebRootPath()).getCanonicalFile();
  1489. File uploadRoot = new File(webRoot, "web/upload").getCanonicalFile();
  1490. File previewFile = normalizedPath.startsWith("/")
  1491. ? new File(webRoot, normalizedPath.substring(1)).getCanonicalFile()
  1492. : new File(webRoot, normalizedPath).getCanonicalFile();
  1493. if (!previewFile.getPath().startsWith(uploadRoot.getPath() + File.separator)) {
  1494. return null;
  1495. }
  1496. return previewFile.isFile() ? previewFile : null;
  1497. }
  1498. private void writePreviewUnavailable() throws Exception {
  1499. write("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>"
  1500. + "body{margin:0;font-family:Arial,'Microsoft YaHei',sans-serif;background:#f5f7fa;color:#606266;}"
  1501. + ".msg{padding:80px 20px;text-align:center;font-size:14px;}"
  1502. + "</style></head><body><div class=\"msg\">预览内容不存在,请刷新预览后再查看。</div></body></html>");
  1503. }
  1504. // 测试的服务
  1505. /**
  1506. * 重置文章运行文件,主要是替换链接的域名,固定替换为 space.apps.moudules.website.common.ConstVars.domain
  1507. *
  1508. * @return
  1509. * @throws Exception
  1510. * @author 陈锋
  1511. * @log 2020年10月19日
  1512. */
  1513. public String resetArticleRunHtmlLink() throws Exception {
  1514. GeneralDBAccess gdba = getGdbaInstance();
  1515. SqlCommandImpl sqlCmd = new SqlCommandImpl("select * from article ");
  1516. @SuppressWarnings("unchecked")
  1517. List<Article> articleList = gdba.selectAsList(sqlCmd, Article.class);
  1518. String webPath = getWebRootPath();
  1519. for (Article article : articleList) {
  1520. File file = new File(webPath + article.getContent());
  1521. if (".DS_Store".equals(file.getName())) {
  1522. continue;
  1523. }
  1524. if (!file.isFile()) {
  1525. continue;
  1526. }
  1527. String content = converArticleContentHtmlLink(file, space.apps.moudules.website.common.ConstVars.domain,
  1528. webPath);
  1529. FileUtil.writeFile(content, file.getPath());
  1530. }
  1531. ResponsePackage rp = getResponseSuccessPackage();
  1532. setResponsePackage(rp);
  1533. return DEFAULT_FORWARD;
  1534. }
  1535. /**
  1536. * 转换文章内容 html 里的链接
  1537. *
  1538. * @param path
  1539. * @param domain
  1540. * @return
  1541. * @throws Exception
  1542. * @author 陈锋
  1543. * @log 2020年10月16日
  1544. */
  1545. private String converArticleContentHtmlLink(File input, String domain, String webPath) throws Exception {
  1546. Document doc = Jsoup.parse(input, "UTF-8", "");
  1547. Elements srcEles = doc.select("img[src]");
  1548. Elements originalEles = doc.select("img[data-original]");
  1549. Elements mediaSrcEles = doc.select("iframe[src], embed[src], object[src]");
  1550. Elements objectDataEles = doc.select("object[data]");
  1551. Elements hrefEles = doc.select("a[href]");
  1552. replaceAllHtmlLink(srcEles, "src", domain);
  1553. replaceAllHtmlLink(originalEles, "data-original", domain);
  1554. replaceAllHtmlLink(mediaSrcEles, "src", domain);
  1555. replaceAllHtmlLink(objectDataEles, "data", domain);
  1556. replaceAllHtmlLink(hrefEles, "href", domain);
  1557. imgSrcConverLazyloadSrc(doc);
  1558. normalizePreviewArticleImages(doc);
  1559. String html = doc.select("body").eq(0).html();
  1560. String articleTemplate = html;
  1561. if (html.indexOf("jquery-lazyload-container") == -1) {
  1562. articleTemplate = FileUtil.readFile(webPath + "/main/apps/template/article_issue_template.txt");
  1563. articleTemplate = articleTemplate.replace("{article_content}", html);
  1564. }
  1565. return articleTemplate;
  1566. }
  1567. /**
  1568. * 替换全部链接
  1569. *
  1570. * @param attrEles
  1571. * @param attr
  1572. * @param domain
  1573. * @author 陈锋
  1574. * @log 2020年10月19日
  1575. */
  1576. private void replaceAllHtmlLink(Elements attrEles, String attr, String domain) {
  1577. for (Element ele : attrEles) {
  1578. if (ele.tagName().equalsIgnoreCase("img")) {
  1579. ele.removeAttr("width");
  1580. ele.removeAttr("height");
  1581. ele.removeAttr("style");
  1582. ele.removeAttr("title");
  1583. ele.removeAttr("alt");
  1584. ele.removeAttr("onload");
  1585. ele.removeAttr("border");
  1586. ele.removeAttr("vspace");
  1587. resetParentsPTagStyle(ele);
  1588. }
  1589. String attrValue = ele.attr(attr);
  1590. if (StringUtil.isNull(attrValue)) {
  1591. continue;
  1592. }
  1593. if (attrValue.startsWith("http://42.247.50.199")) {
  1594. attrValue = attrValue.replace("http://42.247.50.199", "");
  1595. } else {
  1596. if (shouldKeepOriginalAttrValue(attrValue)) {
  1597. continue;
  1598. }
  1599. }
  1600. attrValue = FileUtil.replacePathSprit(attrValue);
  1601. if (domain.endsWith("/") && attrValue.startsWith("/")) {
  1602. attrValue = domain + attrValue.substring(1);
  1603. } else {
  1604. attrValue = domain + attrValue;
  1605. }
  1606. if ("href".equals(attr)) {
  1607. ele.attr("target", "_blank");
  1608. }
  1609. ele.attr(attr, attrValue);
  1610. }
  1611. }
  1612. /**
  1613. * 只替换 img 标签上的 p 标签,p 标签加 style="text-align: center"
  1614. *
  1615. * @param imgEle
  1616. * @author 陈锋
  1617. * @log 2020年10月19日
  1618. */
  1619. private void resetParentsPTagStyle(Element imgEle) {
  1620. Element parentEle = imgEle.parent();
  1621. for (int i = 0; i < 6; i++) {
  1622. if (parentEle == null) {
  1623. return;
  1624. }
  1625. if (!parentEle.tagName().equals("p")) {
  1626. parentEle = parentEle.parent();
  1627. } else {
  1628. parentEle.attr("style", "text-align: center");
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. @Override
  1634. public boolean isNextServiceFlag() {
  1635. String nsFlag = this.getRequest().getParameter("nextServiceFormFlag");
  1636. return StringUtil.notNull(nsFlag) && nsFlag.equals("true");
  1637. }
  1638. }