ArticleService.java 73 KB

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