ArticleService.java 78 KB

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