| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847 |
- package space.apps.moudules.website.services;
- import java.io.File;
- import java.net.URLEncoder;
- import java.nio.charset.StandardCharsets;
- import java.sql.Timestamp;
- import java.text.ParseException;
- import java.util.ArrayList;
- import java.util.Base64;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.regex.Pattern;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import org.jsoup.select.Elements;
- import apps.pojo.Article;
- import apps.pojo.ArticleCopy;
- import apps.pojo.ArticleJumpTypeCode;
- import apps.pojo.Website;
- import apps.pojo.WebsiteNavigation;
- import space.apps.common.ConstVars.dataStatusCode;
- import space.apps.moudules.sys.utils.ChangeLogUtil;
- import space.apps.moudules.website.common.ConstVars.articleJumpTypeCode;
- import space.apps.moudules.website.common.ConstVars.articleStatusCode;
- import space.apps.moudules.website.template.util.WebsiteTemplateArticleUtil;
- import space.apps.moudules.website.template.util.WebsiteTemplateNavUtil;
- import space.apps.moudules.website.template.util.WebsiteUtil;
- import space.apps.moudules.website.util.AppWebsiteManageUtil;
- import space.core.apps.common.BaseTransaction;
- import space.core.apps.common.ConstVars;
- import space.core.apps.common.ScheduleImpl;
- import space.core.apps.common.bean.AppUser;
- import space.core.apps.common.bean.NextService;
- import space.core.apps.common.bean.ResponsePackage;
- import space.core.apps.util.GdbaQueryUtil;
- import space.core.apps.util.NextServiceUtil;
- import space.core.apps.util.WebEditorUtil;
- import space.core.common.utils.DateTimeUtil;
- import space.core.common.utils.FileUtil;
- import space.core.common.utils.GsonUtil;
- import space.core.common.utils.PojoUtil;
- import space.core.common.utils.StringUtil;
- import space.core.db.jdbc.GeneralDBAccess;
- import space.core.db.jdbc.SqlCommandImpl;
- /**
- * 文章服务类
- *
- * @author SPACE
- * @date 2020年02月08日
- */
- public class ArticleService extends BaseTransaction {
- static Logger log = LogManager.getLogger(ArticleService.class);
- private static final long serialVersionUID = 1L;
- private static final String ARTICLE_PREVIEW_SESSION_PREFIX = "articlePreviewPath_";
- private static final String PREVIEW_RUN_PATH_KEY = "runPath";
- private static final String PREVIEW_TITLE_KEY = "title";
- private static final String PREVIEW_SOURCE_KEY = "source";
- private static final String PREVIEW_DESC_KEY = "desc";
- private static final String PREVIEW_NAVIGATION_ID_KEY = "navigationid";
- private static final String PREVIEW_WEBSITE_ID_KEY = "websiteid";
- private static final String PREVIEW_RELEASE_TIME_KEY = "releaseTime";
- private static final Pattern LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN = Pattern.compile(
- "(?i)(?:https?:)?//(?:ht\\.gzhxtc\\.edu\\.cn|localhost|127\\.0\\.0\\.1|ffkj-[a-z0-9-]+\\.localhost)(?::\\d+)?(/web/upload/[^\"'<>\\s]*)");
- private static final Long NAVIGATION_STYLE_GRAPHIC_LIST = 10010L;
- private static final String COLLEGE_RED_TEMPLATE_ID_CODE = "ffkjcollegered1";
- private static final String ARTICLE_PUBLISHED_HISTORY_ROOT = "/web/upload/article-history/";
- private static final String PUBLISHED_CONTENT_SNAPSHOT_FIELD = "publishedContentSnapshot";
- private static final String PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD = "publishedEditContentSnapshot";
- /**
- * 转换文章内容 html 里的链接
- *
- * @param path
- * @param domain
- * @return
- * @throws Exception
- * @author 陈锋
- * @log 2020年10月16日
- */
- private String converArticleContentHtmlLink(String path, String domain) throws Exception {
- File input = new File(path);
- Document doc = Jsoup.parse(input, "UTF-8", "");
- replaceHtmlLink(doc, domain);
- imgSrcConverLazyloadSrc(doc);
- normalizePreviewArticleImages(doc);
- String html = doc.select("body").eq(0).html();
- String articleTemplate = FileUtil.readFile(
- getWebRootPath() + space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_PATH);
- articleTemplate = articleTemplate
- .replace(space.apps.moudules.website.common.ConstVars.ARTICLE_RUN_FILE_TEMPLATE_CONTENT_KEY, html);
- return articleTemplate;
- }
- /**
- * 替换 html 的链接
- *
- * @param doc
- * @param domain
- * @author 陈锋
- * @log 2020年10月16日
- */
- private void replaceHtmlLink(Document doc, String domain) {
- Elements srcEles = doc.select("[src]");
- Elements dataEles = doc.select("object[data]");
- Elements hrefEles = doc.select("a[href]");
- replaceAttrPrefix(srcEles, "src", domain);
- replaceAttrPrefix(dataEles, "data", domain);
- replaceAttrPrefix(hrefEles, "href", domain);
- }
- /**
- * 替换属性的前缀
- *
- * @param attrEles 属性标签集合
- * @param attr 属性名
- * @param prefix 前缀
- * @author 陈锋
- * @log 2020年10月16日
- */
- private void replaceAttrPrefix(Elements attrEles, String attr, String prefix) {
- for (Element ele : attrEles) {
- String attrValue = ele.attr(attr);
- if (StringUtil.isNull(attrValue)) {
- continue;
- }
- if (shouldKeepOriginalAttrValue(attrValue)) {
- continue;
- }
- if (prefix.endsWith("/") && attrValue.startsWith("/")) {
- attrValue = prefix + attrValue.substring(1);
- } else {
- attrValue = prefix + attrValue;
- }
- ele.attr(attr, attrValue);
- }
- }
- private boolean shouldKeepOriginalAttrValue(String attrValue) {
- if (StringUtil.isNull(attrValue)) {
- return true;
- }
- String value = attrValue.trim().toLowerCase();
- return value.startsWith("http://") || value.startsWith("https://") || value.startsWith("//")
- || value.startsWith("data:") || value.startsWith("blob:") || value.startsWith("mailto:")
- || value.startsWith("tel:") || value.startsWith("javascript:") || value.startsWith("#");
- }
- /**
- * img 标签的 src 转为 jquery.lazyload.js 的懒加载的 data-original 属性
- *
- * @param doc
- * @author 陈锋
- * @log 2020年10月16日
- */
- private void imgSrcConverLazyloadSrc(Document doc) {
- Elements srcEles = doc.select("img[src]");
- int i = 0;
- for (Element ele : srcEles) {
- i++;
- if (i <= 3) {
- continue;
- }
- String srcValue = ele.attr("src");
- ele.removeAttr("src");
- ele.attr("data-original", srcValue);
- }
- }
- /**
- * 保留手填摘要;未填写摘要时允许为空,不再从正文自动提取。
- *
- * @param article 文章
- * @param htmlContent html 正文内容
- * @author 陈锋
- * @log 2020年10月19日
- */
- private void saveArticleDesc(Article article, String htmlContent) {
- }
- /**
- * 文章录入
- *
- * @return
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- public String add() throws Exception {
- AppUser appUser = getAppUser();
- GeneralDBAccess gdba = getGdbaInstance();
- Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
- String top = getParameter("top");
- String timeSwitch = getParameter("timeSwitch");
- String content = getParameterNotXSS("body");
- Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class);
- String navIdList = getParameter("navIdList");
- WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
- if (wn == null) {
- return DEFAULT_FORWARD;
- }
- if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) {
- return DEFAULT_FORWARD;
- }
- if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) {
- return DEFAULT_FORWARD;
- }
- String editPath = WebEditorUtil.createHtmlFile(content);
- String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath,
- space.apps.moudules.website.common.ConstVars.domain);
- String runPath = WebEditorUtil.createHtmlFile(runContent);
- article.setContent(runPath);// 运行文件
- article.setEditContent(editPath);// 编辑文件
- article.setUnitid(appUser.getUnitId());
- article.setDcode(dataStatusCode.INSERT.getCode());
- article.setCreatePid(appUser.getUserId());
- article.setLastChangePid(appUser.getUserId());
- article.setCreateTime(nowTimestamp);
- // article.setReleaseTime(nowTimestamp);
- article.setLastChangeTime(nowTimestamp);
- article.setSticktop("yes".equals(top) ? 1L : 0L);
- article.setAscode(articleStatusCode.STAY_RELEASE.getCode());// 必填的
- article.setWebsiteid(wn.getWebsiteid());
- article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
- if (!article.getAjtcode().equals(10020L)) {
- article.setUrl(WebsiteTemplateArticleUtil.getArticleURL(wn));
- }
- // if (StringUtil.isNull(article.getReleaseTime())) {
- // article.setReleaseTime(nowTimestamp);
- // }
- saveArticleDesc(article, content);
- gdba.insertByBean(article);
- saveArticleCopy(gdba, article, appUser, navIdList);
- initArticleSticktopSchedule(gdba, article, appUser);
- initArticleReleaseTaskSchedule(gdba, article, appUser);
- gdba.updateById(article);
- setArticleApplyService(article.getArticleid());
- gdba.commit();
- setResponsePackage(getResponseSuccessMsgPackage());
- return DEFAULT_FORWARD;
- }
- /**
- * 设置文章申请服务
- *
- * @param articleid 文章 id
- * @author 陈锋
- * @log 2020年12月8日 下午8:28:18
- */
- private void setArticleApplyService(Long articleid) {
- // 设置下一个服务对象
- if (isNextServiceFlag()) {
- Map<String, Object> paramsMap = NextServiceUtil.newHashMap();
- paramsMap.put("articleid", articleid);
- NextService nextService = NextServiceUtil.getLayer("website.article_start", "sys.common_audit.apply", paramsMap);
- nextService.setRefresh(true); // 需要刷新
- setNextService(nextService);
- }
- }
- /**
- * 文章修改
- *
- * @return
- * @throws Exception
- * @author 陈锋
- * @log 2020年9月18日
- */
- public String modify() throws Exception {
- GeneralDBAccess gdba = getGdbaInstance();
- AppUser appUser = getAppUser();
- Article a2 = new Article();
- a2.setArticleid(getParameterToLong("articleid"));
- gdba.selectById(a2);
- if (!Long.valueOf(dataStatusCode.INSERT.getCode()).equals(a2.getDcode())) {
- // setResponsePackage(getResponseErrorMsgPackage());
- StringBuilder msgBuilder = new StringBuilder();
- msgBuilder.append("[").append(DateTimeUtil.getNowDate()).append("] - 文章修改,ip为:")
- .append(getRequest().getLocalAddr()).append(" 篡改的文章 id 为:").append(a2.getArticleid())
- .append(",文章标题为:").append(a2.getTitle());
- log.error(msgBuilder.toString());
- return ERROR_FORWARD;
- }
- Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
- String top = getParameter("top");
- String timeSwitch = getParameter("timeSwitch");
- String content = getParameterNotXSS("body");
- String navIdList = getParameter("navIdList");
- Article article = new Article();
- article.setArticleid(a2.getArticleid());
- gdba.selectById(article);
- PojoUtil.formatRequest(getRequest(), article);
- WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
- if (wn == null) {
- return DEFAULT_FORWARD;
- }
- if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) {
- return DEFAULT_FORWARD;
- }
- if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) {
- return DEFAULT_FORWARD;
- }
- article.setSticktop("yes".equals(top) ? 1L : 0L);
- ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(), GsonUtil.toJson(a2));
- FileUtil.writeFile(content, getWebRootPath() + a2.getEditContent());// 编辑文件,获取页面上的正文内容
- String runContent = converArticleContentHtmlLink(getWebRootPath() + a2.getEditContent(),
- space.apps.moudules.website.common.ConstVars.domain);
- FileUtil.writeFile(runContent, getWebRootPath() + a2.getContent());// 运行文件,从编辑文件里转换为运行文件
- article.setLastChangePid(appUser.getUserId());
- article.setLastChangeTime(nowTimestamp);
- article.setWebsiteid(wn.getWebsiteid());
- article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
- // 旧的文章是定时发布的,新的文章不是定时发布的,则需要把发布时间设置为空
- if (a2.getRelease().equals(1L) && !"yes".equals(timeSwitch)) {
- article.setReleaseTime(null);
- }
- verifyArticleUrl(article, a2, wn);
- saveArticleDesc(article, content);
- gdba.updateById(article);
- saveArticleCopy(gdba, article, appUser, navIdList);
- initArticleSticktopSchedule(gdba, article, appUser);
- initArticleReleaseTaskSchedule(gdba, article, appUser);
- gdba.updateById(article);
- setArticleApplyService(article.getArticleid());
- gdba.commit();
- setResponsePackage(getResponseSuccessMsgPackage());
- return DEFAULT_FORWARD;
- }
- /**
- * 根据栏目 id 获取栏目对象
- *
- * @param gdba
- * @param navigationId 栏目 id
- * @return
- * @throws Exception
- * @author 陈锋
- * @log 2020年9月26日
- */
- private WebsiteNavigation getWebsiteNavigationById(GeneralDBAccess gdba, Long navigationId) throws Exception {
- WebsiteNavigation wn = new WebsiteNavigation();
- wn.setNavigationid(navigationId);
- gdba.selectById(wn);
- return wn;
- }
- private WebsiteNavigation getArticleTargetNavigation(GeneralDBAccess gdba, Long navigationId, String targetName)
- throws Exception {
- if (navigationId == null || navigationId <= 0) {
- setResponsePackage(getResponseWarningMsgPackage("请选择" + targetName));
- return null;
- }
- WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationId);
- if (!isArticleTargetNavigation(wn)) {
- setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择可发布文章的栏目"));
- return null;
- }
- if (hasEnabledChildNavigation(gdba, navigationId)) {
- setResponsePackage(getResponseWarningMsgPackage(targetName + "必须选择最下级栏目,请继续向右选择最后一级栏目"));
- return null;
- }
- return wn;
- }
- private boolean verifyArticleCopyNavigationList(GeneralDBAccess gdba, String navIdList, Article article)
- throws Exception {
- if (StringUtil.isNull(navIdList)) {
- return true;
- }
- Set<String> navIdSet = new HashSet<String>();
- String[] navIdAry = navIdList.split(",");
- for (String navId : navIdAry) {
- if (StringUtil.isNull(navId) || navIdSet.contains(navId)) {
- continue;
- }
- navIdSet.add(navId);
- WebsiteNavigation wn = getArticleTargetNavigation(gdba, Long.valueOf(navId), "抄送栏目");
- if (wn == null) {
- return false;
- }
- if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "抄送栏目")) {
- return false;
- }
- }
- return true;
- }
- private boolean verifyGraphicListThumbnailRequired(GeneralDBAccess gdba, WebsiteNavigation wn, Article article,
- String targetName) throws Exception {
- if (wn == null || !NAVIGATION_STYLE_GRAPHIC_LIST.equals(wn.getWnlscode())) {
- return true;
- }
- if (article != null && StringUtil.notNull(article.getThumbnail())) {
- return true;
- }
- setResponsePackage(getResponseWarningMsgPackage(targetName + "为图文列表时必须上传缩略图"));
- return false;
- }
- private boolean isCollegeRedGraphicListNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception {
- if (wn == null || !NAVIGATION_STYLE_GRAPHIC_LIST.equals(wn.getWnlscode())) {
- return false;
- }
- return isCollegeRedTemplateNavigation(gdba, wn);
- }
- private boolean isCollegeRedTemplateNavigation(GeneralDBAccess gdba, WebsiteNavigation wn) throws Exception {
- Long wtid = wn == null ? null : wn.getWtid();
- if (wtid == null && wn != null && wn.getWebsiteid() != null) {
- Website website = WebsiteUtil.getWebsiteByID(gdba, wn.getWebsiteid());
- wtid = website == null ? null : website.getWtid();
- }
- if (wtid == null) {
- return false;
- }
- return isCollegeRedTemplateIdCode(gdba, wtid);
- }
- private boolean isCollegeRedTemplateIdCode(GeneralDBAccess gdba, Long wtid) throws Exception {
- String sql = " select id_code from website_template where wtid = :wtid ";
- SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
- sqlCmd.setString("wtid", wtid);
- Map<String, Object> templateMap = gdba.selectAsMap(sqlCmd);
- Object idCode = templateMap == null ? null : templateMap.get("id_code");
- return idCode != null && idCode.toString().indexOf(COLLEGE_RED_TEMPLATE_ID_CODE) >= 0;
- }
- private boolean isArticleTargetNavigation(WebsiteNavigation wn) {
- if (wn == null || wn.getWntcode() == null) {
- return false;
- }
- return isArticleTargetWntcode(wn.getWntcode());
- }
- private boolean isArticleTargetWntcode(Object wntcode) {
- if (wntcode == null) {
- return false;
- }
- Long wntcodeLong = Long.valueOf(wntcode.toString());
- return Long.valueOf(10010L).equals(wntcodeLong) || Long.valueOf(10060L).equals(wntcodeLong);
- }
- private boolean hasEnabledChildNavigation(GeneralDBAccess gdba, Long navigationId) throws Exception {
- String sql = " select count(*) as c from website_navigation where dcode = 61 and parent_nid = :navigationid ";
- SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
- sqlCmd.setString("navigationid", navigationId);
- Map<String, Object> resultMap = gdba.selectAsMap(sqlCmd);
- return Integer.parseInt(resultMap.get("c").toString()) > 0;
- }
- /**
- * 验证文章的 url 是否需要生成新的、或使用旧的、或使用页面上的
- *
- * @param newArticle 新文章对象(也就是更新的)
- * @param oldArticle 旧文章对象
- * @param newArticleNavigation 新文章的的栏目对象
- * @throws Exception
- * @author 陈锋
- * @log 2020年10月11日
- */
- private void verifyArticleUrl(Article newArticle, Article oldArticle, WebsiteNavigation newArticleNavigation)
- throws Exception {
- // 新、旧都是一样
- if (oldArticle.getAjtcode().equals(newArticle.getAjtcode())) {
- // 都是正文、无动作,则使用旧的 url
- if (!oldArticle.getAjtcode().equals(10020L)) {// 不是链接
- newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
- }
- // 都是链接时,则使用页面的,使用页面的不用重新设置 url
- }
- // 旧的是链接,新的不是链接时,则需要生成 url
- else if (oldArticle.getAjtcode().equals(10020L) && !newArticle.getAjtcode().equals(10020L)) {
- newArticle.setUrl(WebsiteTemplateArticleUtil.getArticleURL(newArticleNavigation));// 生成新的 url
- }
- // 新的为无动作,则使用旧的
- else if (newArticle.getAjtcode().equals(10030L)) {
- newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
- }
- // url 为空时,则用旧的
- else if (newArticle.getUrl() == null) {
- newArticle.setUrl(oldArticle.getUrl());// 使用旧的 url
- }
- }
- /**
- * 设置文章变动申请服务
- *
- * @param articleid 文章 id
- * @author 陈锋
- * @log 2020年12月8日 下午8:28:18
- */
- private void setArticleChangeApplyService(Long articleid) {
- // 设置下一个服务对象
- if (isNextServiceFlag()) {
- Map<String, Object> paramsMap = NextServiceUtil.newHashMap();
- paramsMap.put("articleid", articleid);
- NextService nextService = NextServiceUtil.getLayer("website.article_start_change", "sys.common_audit.change_apply", paramsMap);
- nextService.setRefresh(true); // 需要刷新
- setNextService(nextService);
- }
- }
- /**
- * 文章变动
- *
- * @return
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- public String change() throws Exception {
- AppUser appUser = getAppUser();
- GeneralDBAccess gdba = getGdbaInstance();
- Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
- String top = getParameter("top");
- String timeSwitch = getParameter("timeSwitch");
- String content = getParameterNotXSS("body");
- String navIdList = getParameter("navIdList");
- Article article = new Article();
- article.setArticleid(getParameterToLong("articleid"));
- gdba.selectById(article);
- PojoUtil.formatRequest(getRequest(), article);
- WebsiteNavigation wn = getArticleTargetNavigation(gdba, article.getNavigationid(), "发布栏目");
- if (wn == null) {
- return TIPS_FORWARD;
- }
- if (!verifyGraphicListThumbnailRequired(gdba, wn, article, "发布栏目")) {
- return TIPS_FORWARD;
- }
- if (!verifyArticleCopyNavigationList(gdba, navIdList, article)) {
- return TIPS_FORWARD;
- }
- article.setSticktop("yes".equals(top) ? 1L : 0L);
- Article a2 = new Article();
- a2.setArticleid(article.getArticleid());
- gdba.selectById(a2);
- ChangeLogUtil.addChangeLog(gdba, appUser, "Article", a2.getArticleid(),
- buildArticleChangeLogContent(a2, nowTimestamp));
- verifyArticleUrl(article, a2, wn);
- FileUtil.writeFile(content, getWebRootPath() + a2.getEditContent());// 编辑文件,获取页面上的正文内容
- String runContent = converArticleContentHtmlLink(getWebRootPath() + a2.getEditContent(),
- space.apps.moudules.website.common.ConstVars.domain);
- FileUtil.writeFile(runContent, getWebRootPath() + a2.getContent());// 运行文件,从编辑文件里转换为运行文件
- article.setDcode(dataStatusCode.STAY_SUBMIT.getCode());
- article.setLastChangePid(appUser.getUserId());
- article.setLastChangeTime(nowTimestamp);
- article.setWebsiteid(wn.getWebsiteid());
- article.setRelease("yes".equals(timeSwitch) ? 1L : 0L);
- // 旧的文章设置了定时发布、发布时间,为到指定的发布时间时
- if (articleStatusCode.STAY_RELEASE.getCode().equals(a2.getAscode()) && a2.getRelease().equals(1L)
- && StringUtil.notNull(a2.getReleaseTaskSchedulesid())) {
- // 新的文章没有设置定时发布
- if (article.getRelease().equals(0L)) {
- article.setReleaseTime(null);
- }
- }
- saveArticleDesc(article, content);
- saveArticleCopy(gdba, article, appUser, navIdList);
- initArticleSticktopSchedule(gdba, article, appUser);
- initArticleReleaseTaskSchedule(gdba, article, appUser);
- gdba.updateById(article);
- setArticleChangeApplyService(article.getArticleid());
- gdba.commit();
- setResponsePackage(getResponseSuccessMsgPackage());
- return TIPS_FORWARD;
- }
- private String buildArticleChangeLogContent(Article article, Timestamp snapshotTime) throws Exception {
- JsonObject logContent = new JsonParser().parse(GsonUtil.toJson(article)).getAsJsonObject();
- if (!isPublishedArticle(article)) {
- return logContent.toString();
- }
- String contentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getContent(), "content",
- snapshotTime);
- if (StringUtil.notNull(contentSnapshot)) {
- logContent.addProperty(PUBLISHED_CONTENT_SNAPSHOT_FIELD, contentSnapshot);
- }
- String editContentSnapshot = copyPublishedArticleFile(article.getArticleid(), article.getEditContent(),
- "edit-content", snapshotTime);
- if (StringUtil.notNull(editContentSnapshot)) {
- logContent.addProperty(PUBLISHED_EDIT_CONTENT_SNAPSHOT_FIELD, editContentSnapshot);
- }
- return logContent.toString();
- }
- private boolean isPublishedArticle(Article article) {
- return Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode())
- && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode());
- }
- private String copyPublishedArticleFile(Long articleid, String filePath, String fileType, Timestamp snapshotTime)
- throws Exception {
- if (StringUtil.isNull(filePath)) {
- return null;
- }
- File source = new File(getWebRootPath() + filePath);
- if (!source.exists() || !source.isFile()) {
- return null;
- }
- String snapshotDir = ARTICLE_PUBLISHED_HISTORY_ROOT + articleid + "/";
- FileUtil.makeDirectory(new File(getWebRootPath() + snapshotDir));
- String fileExt = FileUtil.getFileExt(filePath);
- if (StringUtil.isNull(fileExt)) {
- fileExt = "html";
- } else if (fileExt.startsWith(".")) {
- fileExt = fileExt.substring(1);
- }
- String snapshotPath = snapshotDir + DateTimeUtil.formatDate(snapshotTime, "yyyyMMddHHmmssSSS") + "-"
- + fileType + "." + fileExt;
- FileUtil.copyFile(source.getAbsolutePath(), getWebRootPath() + snapshotPath);
- return snapshotPath;
- }
- /**
- * 删除指定文章的所有抄送记录
- *
- * @param gdba
- * @param article
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- private void delArticleCopy(GeneralDBAccess gdba, Article article) throws Exception {
- String sql = " delete from article_copy where articleid = :articleid ";
- SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
- sqlCmd.setString("articleid", article.getArticleid());
- gdba.modify(sqlCmd);
- }
- /**
- * 查询指定文章所抄送的栏目列表
- *
- * @param gdba
- * @param article
- * @return
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- private List<Map<String, Object>> getArticleCopyList(GeneralDBAccess gdba, Article article) throws Exception {
- String sql = " SELECT wn.navigationid, wn.name, wn.parent_nid, ac.dcode FROM article_copy ac, website_navigation wn where ac.navigationid =" +
- " wn.navigationid and ac.articleid = :articleid ";
- SqlCommandImpl sqlCmd = new SqlCommandImpl(sql);
- sqlCmd.setString("articleid", article.getArticleid());
- return gdba.selectAsMapList(sqlCmd);
- }
- /**
- * 获取可以抄送的栏目
- *
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- public void getCopyNavigation() throws Exception {
- GeneralDBAccess gdba = getGdbaInstance();
- AppUser appUser = getAppUser();
- List<Map<String, Object>> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser,
- 10010L);
- ResponsePackage rp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList));
- write(rp.toJsonWriteNonStringValueAsString());
- // getWriter().write(FastjsonUtil.toStringJSON(getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList))));
- }
- /**
- * 获取可以发布的栏目
- *
- * @throws Exception
- * @author SPACE
- * @date 2020年02月08日
- */
- public void getIssueNavigation() throws Exception {
- GeneralDBAccess gdba = getGdbaInstance();
- AppUser appUser = getAppUser();
- List<Map<String, Object>> navigationList = AppWebsiteManageUtil.getManageNavigationListByAppUser(gdba, appUser,
- 10000L);
- ResponsePackage rsdp = getResponseSuccessDataPackage(getNavigationMap(gdba, navigationList));
- write(rsdp.toJsonWriteNonStringValueAsString());
- }
- /**
- * 将栏目的名称修改为:上级栏目链/栏目名称
- *
- * @param gdba
- * @param navigationList
- * @throws Exception
- * @author SPACE
- * @date 2020年02月27日
- */
- void getNavAllParentName(GeneralDBAccess gdba, List<Map<String, Object>> navigationList) throws Exception {
- for (Map<String, Object> map : navigationList) {
- Object parNid = map.get("parent_nid");
- if (StringUtil.isNull(parNid)) {
- continue;
- }
- map.put("name", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString())));
- }
- }
- /**
- * 根据栏目ID获取栏目上级链名称
- *
- * @param gdba 数据库
- * @param navID 栏目ID
- * @throws Exception
- * @author SPACE
- * @date 2020年02月27日
- */
- String getNavAllParentName(GeneralDBAccess gdba, Long navID) throws Exception {
- List<WebsiteNavigation> navParentList = WebsiteTemplateNavUtil.getNavParentList(gdba, navID);
- if (navParentList.size() == 1) {
- return navParentList.get(0).getName();
- }
- StringBuilder nameBuilder = new StringBuilder();
- for (WebsiteNavigation wn : navParentList) {
- nameBuilder.append(wn.getName()).append(" / ");
- }
- return nameBuilder.substring(0, nameBuilder.length() - 2);
- }
- Map<String, Object> getNavigationMap(GeneralDBAccess gdba, List<Map<String, Object>> navigationList)
- throws Exception {
- Map<String, Object> retMap = new HashMap<String, Object>();
- if (navigationList == null || navigationList.size() == 0) {
- retMap.put("data", new ArrayList<Map<String, Object>>());
- return retMap;
- }
- Set<String> websiteSet = new HashSet<String>();
- Map<String, List<Map<String, Object>>> websiteNavigationMap = new LinkedHashMap<String, List<Map<String, Object>>>();
- for (Map<String, Object> map : navigationList) {
- String website = map.get("websiteid").toString();
- websiteSet.add(website);
- List<Map<String, Object>> websiteNavigationList = websiteNavigationMap.get(website);
- if (websiteNavigationList == null) {
- websiteNavigationList = new ArrayList<Map<String, Object>>();
- websiteNavigationMap.put(website, websiteNavigationList);
- }
- websiteNavigationList.add(map);
- }
- if (websiteSet.size() > 1) {
- List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
- for (String websiteId : websiteNavigationMap.keySet()) {
- Website w = new Website();
- w.setWebsiteid(Long.valueOf(websiteId));
- gdba.selectById(w);
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("navigationid", "-1");
- map.put("name", w.getName());
- map.put("children", buildNavigationTree(websiteNavigationMap.get(websiteId)));
- dataList.add(map);
- }
- retMap.put("data", dataList);
- } else {
- retMap.put("data", buildNavigationTree(navigationList));
- }
- return retMap;
- }
- List<Map<String, Object>> buildNavigationTree(List<Map<String, Object>> navigationList) {
- Map<String, Map<String, Object>> navigationMap = new LinkedHashMap<String, Map<String, Object>>();
- for (Map<String, Object> navigation : navigationList) {
- Map<String, Object> item = new HashMap<String, Object>(navigation);
- item.remove("children");
- navigationMap.put(item.get("navigationid").toString(), item);
- }
- List<Map<String, Object>> rootList = new ArrayList<Map<String, Object>>();
- for (Map<String, Object> navigation : navigationMap.values()) {
- Object parentNid = navigation.get("parent_nid");
- Map<String, Object> parent = parentNid == null ? null : navigationMap.get(parentNid.toString());
- if (parent == null) {
- rootList.add(navigation);
- continue;
- }
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
- if (children == null) {
- children = new ArrayList<Map<String, Object>>();
- parent.put("children", children);
- }
- children.add(navigation);
- }
- setDisabledNavigationList(rootList);
- return rootList;
- }
- private void setDisabledNavigationList(List<Map<String, Object>> navigationList) {
- for (Map<String, Object> navigation : navigationList) {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> children = (List<Map<String, Object>>) navigation.get("children");
- if (children != null && children.size() > 0) {
- setDisabledNavigationList(children);
- continue;
- }
- if (!isArticleTargetWntcode(navigation.get("wntcode"))) {
- navigation.put("disabled", true);
- }
- }
- }
- /**
- * 文章信息
- *
- * @return
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- public String info() throws Exception {
- Article article = (Article) PojoUtil.formatRequest(getRequest(), Article.class);
- GeneralDBAccess gdba = getGdbaInstance();
- gdba.selectById(article);
- List<Map<String, Object>> articleCopyList = getArticleCopyList(gdba, article);
- getNavAllParentName(gdba, articleCopyList);
- String navAllName = getNavAllParentName(gdba, article.getNavigationid());
- Website website = new Website();
- website.setWebsiteid(article.getWebsiteid());
- gdba.selectById(website);
- if (!articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode())
- || (articleJumpTypeCode.CUSTOM_LINK.getCode().equals(article.getAjtcode())
- && article.getUrl().startsWith("/"))) {
- // 设置查看文章时的 url
- String url = appendWebsiteDomain(website.getPort().toString(), website.getDomains(), website.getProtocol(),
- article.getUrl());
- article.setUrl(url);
- }
- boolean isShowModifyReleaseTime = false;// 是否显示修改发布时间,默认不显示
- // 变动时的发布时间,在用状态、已发布
- if (Long.valueOf(dataStatusCode.USE.getCode()).equals(article.getDcode())
- && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) {
- isShowModifyReleaseTime = true;
- }
- // 修改时的发布时间,录入状态、待发布、不是定时发布
- if (Long.valueOf(dataStatusCode.INSERT.getCode()).equals(article.getDcode()) && article.getRelease() == 0L) {
- isShowModifyReleaseTime = true;
- }
- boolean isShowpreview = false;// 是否显示预览,默认不显示
- // 文章数据状态为 在用,文章状态 已发布
- if (article.getDcode().equals(Long.valueOf(dataStatusCode.USE.getCode()))
- && articleStatusCode.HAS_RELEASE.getCode().equals(article.getAscode())) {
- // 文章动作 跳转正文页 或 自定义链接
- if (article.getAjtcode().equals(articleJumpTypeCode.MAIN_BODY.getCode())
- || article.getAjtcode().equals(articleJumpTypeCode.CUSTOM_LINK.getCode())) {
- isShowpreview = true;
- }
- }
- setRequestAttribute("isShowpreview", isShowpreview);// 是否显示预览
- setRequestAttribute("isShowModifyReleaseTime", isShowModifyReleaseTime);// 是否显示修改发布时间
- setRequestAttribute("article", article);
- setRequestAttribute("navAllName", navAllName);
- setRequestAttribute("copyNav", GsonUtil.toJson(articleCopyList));
- WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid());
- String articleContentForPreview;
- try {
- articleContentForPreview = FileUtil.readFile(getWebRootPath() + article.getContent());
- setRequestAttribute("body", articleContentForPreview);
- } catch (Exception e) {
- articleContentForPreview = "内容文件不存在或已被删除";
- setRequestAttribute("body", articleContentForPreview);
- }
- setRequestAttribute("infoPreviewHtmlB64", Base64.getEncoder().encodeToString(
- buildArticleInfoPreviewHtml(article, website, navigation, articleContentForPreview)
- .getBytes(StandardCharsets.UTF_8)));
- try {
- setRequestAttribute("editBody", FileUtil.readFile(getWebRootPath() + article.getEditContent()));
- } catch (Exception e) {
- setRequestAttribute("editBody", "内容文件不存在或已被删除");
- }
- ArticleJumpTypeCode ajtCode = new ArticleJumpTypeCode();
- ajtCode.setAjtcode(article.getAjtcode());
- gdba.selectById(ajtCode);
- setRequestAttribute("ajtCode", ajtCode);// 查看文章时用到
- return DEFAULT_FORWARD;
- }
- /**
- * 拼接网站域名
- *
- * @param port 端口
- * @param domains 域名
- * @param protocol 协议
- * @param catalogURI 目录
- * @return 带有协议和端口的网站域名
- * @author SPACE
- * @log Oct 9, 2020 11:16:33 PM
- */
- private static String appendWebsiteDomain(String port, String domains, String protocol, String catalogURI) {
- String href = null;
- String[] domainsAry = domains.split(";");
- if (domainsAry.length > 0) {
- port = "80".equals(port) ? "" : (":" + port); // 非 80 端口进行特殊处理
- if (domainsAry[0].endsWith("/")) {
- domainsAry[0] = domainsAry[0].substring(0, domainsAry[0].lastIndexOf("/"));
- }
- href = protocol + "://" + domainsAry[0] + port + catalogURI;
- }
- // 未找到域名
- else {
- href = "javascript:alert('website domain is null!');";
- }
- return href;
- }
- /**
- * 文章置顶周期
- *
- * @param article
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- private void initArticleSticktopSchedule(GeneralDBAccess gdba, Article article, AppUser appUser)
- throws ParseException, Exception {
- // 删除掉已经添加了的定时任务
- if (StringUtil.notNull(article.getSticktopSchedulesid())) {
- ScheduleImpl.delSchedule(article.getSticktopSchedulesid(), gdba);
- }
- // 不置顶
- if (article.getSticktop() == 0) {
- article.setSticktopEndTime(null);
- return;
- }
- // 非在用状态
- if (!article.getDcode().equals(61L)) {
- return;
- }
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("articleid", article.getArticleid());
- Long scheduleid = ScheduleImpl.addSchedule(
- "文章“" + article.getArticleid() + "/" + article.getTitle() + "”置顶周期任务",
- DateTimeUtil.formatDateYMdHms(article.getSticktopEndTime()),
- "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleSticktop", appUser.getUserId(),
- data, gdba);
- article.setSticktopSchedulesid(scheduleid);
- }
- /**
- * 文章定时发布任务
- *
- * @param gdba
- * @param article
- * @param appUser
- * @throws Exception
- * @author 陈锋
- * @log 2020年9月16日
- */
- private void initArticleReleaseTaskSchedule(GeneralDBAccess gdba, Article article, AppUser appUser)
- throws Exception {
- // 删掉已经添加的定时发布文章任务
- if (StringUtil.notNull(article.getReleaseTaskSchedulesid())) {
- ScheduleImpl.delSchedule(article.getReleaseTaskSchedulesid(), gdba);
- article.setReleaseTaskSchedulesid(null);
- }
- if (article.getRelease() == 0) {
- // article.setReleaseTime(null);
- return;
- }
- article.setAscode(articleStatusCode.STAY_RELEASE.getCode());
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("articleid", article.getArticleid());
- Long scheduleid = ScheduleImpl.addSchedule(
- "文章“" + article.getArticleid() + "/" + article.getTitle() + "”定时发布任务",
- DateTimeUtil.formatDateYMdHms(article.getReleaseTime()),
- "space.apps.moudules.website.schedule.ArticleScheduleImpl", "articleRelease", appUser.getUserId(), data,
- gdba);
- article.setReleaseTaskSchedulesid(scheduleid);
- }
- /**
- * 文章列表
- *
- * @return
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- public String list() throws Exception {
- AppUser appUser = getAppUser();
- StringBuilder sqlBuilder = new StringBuilder(" Select ");
- sqlBuilder.append(
- " a.articleid, a.dcode, a.thumbnail, (Select name from data_status_code dsc where dsc.dcode = a.dcode) as 'dsname', a.ascode, a" +
- ".websiteid, a.title, a.navigationid, a.ajtcode, a.sticktop, a.release_time, a.read_count, a.create_pid, date_format(a" +
- ".create_time, '%Y-%m-%d') as 'ctime', concat(per.name, ' / ', dep.name) pname_dname ");
- sqlBuilder.append(
- " ,(Select name from website_navigation wn where wn.navigationid = a.navigationid ) as 'navname'");
- sqlBuilder.append(
- " ,(Select name from website w where w.websiteid = a.websiteid ) as 'website_name', dep.departmentid ");
- sqlBuilder.append(" from article a ");
- sqlBuilder.append(" left join person per on a.create_pid = per.personid ");
- sqlBuilder.append(" left join department dep on per.departmentid = dep.departmentid ");
- sqlBuilder.append(
- " where a.unitid = :unitid and if((a.dcode in (11, 21)), (a.create_pid = :createPid), (a.create_pid > 0)) ");
- sqlBuilder.append(" and a.dcode != 72 "); // 过滤已删除的数据
- SqlCommandImpl sqlCmd = new SqlCommandImpl();
- sqlCmd.setString("unitid", appUser.getUnitId()).setString("createPid", appUser.getUserId());
- GdbaQueryUtil.appendLikeSql(sqlBuilder, sqlCmd, "title", getParameter("title")); // 标题
- GdbaQueryUtil.appendFieldSql(sqlBuilder, sqlCmd, "a.dcode", getParameter("dcode")); // 数据状态码
- // 栏目
- String navigation = getParameter("navigation");
- if (StringUtil.notNull(navigation)) {
- sqlBuilder.append("and (" + GdbaQueryUtil.getInSql(sqlCmd, "navigationid", navigation, ",")
- + "or articleid in (Select ac.articleid from website_navigation wn, article_copy ac, article a "
- + "where wn.navigationid = ac.navigationid and a.articleid = ac.articleid and ac.dcode = 61 and a.dcode = 61 "
- + "and wn.dcode = 61 and " + GdbaQueryUtil.getInSql(sqlCmd, "ac.navigationid", navigation, ",")
- + " ))");
- }
- // 我发布的
- String issue = getParameter("issue");
- if (StringUtil.notNull(issue) && ConstVars.TRUE.equals(issue)) {
- sqlBuilder.append(" and a.create_pid = :cpid ");
- sqlCmd.setString("cpid", appUser.getUserId());
- }
- /* 年月日 */
- String dateTime = getParameter("dateTime");
- if (StringUtil.notNull(dateTime)) {
- String[] dateTimeAry = dateTime.split(",");
- sqlBuilder.append(
- " and date_format(release_time, '%Y-%m-%d') >= date_format(:startTime, '%Y-%m-%d') and date_format(release_time, '%Y-%m-%d') <=" +
- " date_format(:endTime, '%Y-%m-%d') ");
- sqlCmd.setString("startTime", dateTimeAry[0]).setString("endTime", dateTimeAry[1]);
- }
- GeneralDBAccess gdba = getGdbaInstance();
- // 获取可管理的网站
- List<Map<String, Object>> manageWebsiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(gdba,
- getAppUser());
- if (manageWebsiteList.size() > 0) {
- sqlBuilder.append(" and ( ").append(GdbaQueryUtil.getInSql(sqlCmd, "a.websiteid",
- AppWebsiteManageUtil.websiteListIDToAry(manageWebsiteList)));
- sqlBuilder.append("or (a.create_pid = :cpid2 )) ");
- } else {
- sqlBuilder.append(" and (a.create_pid = :cpid2 ) ");
- }
- sqlCmd.setString("cpid2", appUser.getUserId());
- // 排序方式
- String sort = getParameter("sort");
- if (StringUtil.isNull(sort) || "sort_new".equals(sort)) {
- sqlBuilder.append(" order by dcode asc, sticktop desc, release_time desc, articleid asc ");
- } else if ("sort_top".equals(sort)) {
- sqlBuilder.append(" order by dcode asc, read_count desc, articleid asc ");
- } else if ("sort_bottom".equals(sort)) {
- sqlBuilder.append(" order by dcode asc, read_count asc, articleid asc ");
- }
- sqlCmd.setExecuteSql(sqlBuilder.toString());
- List<Map<String, Object>> articleList = gdba.selectAsMapList(sqlCmd, getAppsPageBean());
- for (Map<String, Object> map : articleList) {
- // 校验是否拥有该网站的管理权限
- for (Map<String, Object> websiteMap : manageWebsiteList) {
- if (map.get("websiteid").toString().equals(websiteMap.get("websiteid").toString())) {
- map.put("isManagerDepartmentArticleFlag", "true");
- break;
- }
- }
- map.put("navAllName", getNavAllParentName(gdba, Long.valueOf(map.get("navigationid").toString())));
- }
- ResponsePackage rsp = getResponseSuccessPackage();
- rsp.setRequestAttribute("articleList", articleList);
- setResponsePackage(rsp);
- return DEFAULT_FORWARD;
- }
- /**
- * 保存文章抄送
- *
- * @param gdba
- * @param article
- * @param appUser
- * @param navIdList
- * @throws Exception
- * @author SPACE
- * @date 2020年02月09日
- */
- private void saveArticleCopy(GeneralDBAccess gdba, Article article, AppUser appUser, String navIdList)
- throws Exception {
- delArticleCopy(gdba, article);
- if (StringUtil.isNull(navIdList)) {
- return;
- }
- Timestamp nowTimestamp = DateTimeUtil.getNowTimestamp();
- String[] navIdAry = navIdList.split(",");
- Set<String> navIdSet = new HashSet<String>();
- for (String navId : navIdAry) {
- if (navIdSet.contains(navId)) {
- continue;
- }
- navIdSet.add(navId);
- ArticleCopy ac = new ArticleCopy();
- ac.setArticleid(article.getArticleid());
- ac.setNavigationid(Long.valueOf(navId));
- ac.setCreatePid(appUser.getUserId());
- ac.setCreateTime(nowTimestamp);
- ac.setDcode(dataStatusCode.INSERT_AUDIT.getCode());
- gdba.insertByBean(ac);
- }
- }
- /**
- * 文章录入前置服务
- *
- * @return
- * @throws Exception
- * @author SPACE
- * @log Oct 14, 2020 10:32:06 PM
- */
- public String articleAddBefore() throws Exception {
- List<Map<String, Object>> websiteList = AppWebsiteManageUtil.getManageWebsiteListByAppUser(getGdbaInstance(),
- getAppUser());
- // 默认找可管理的第一个网站
- if (websiteList != null && websiteList.size() > 0) {
- setRequestAttribute("article_sources", websiteList.get(0).get("name"));
- }
- return DEFAULT_FORWARD;
- }
- /**
- * 生成文章正文临时预览。
- *
- * @throws Exception
- * @author SPACE
- */
- public void preview() throws Exception {
- String content = getParameterNotXSS("body");
- String title = getParameterNotXSS("title");
- String source = getParameterNotXSS("source");
- String desc = getParameterNotXSS("desc");
- Long navigationid = getParameterToLong("navigationid");
- if (StringUtil.isNull(content)) {
- write(getResponseWarningMsgPackage("正文内容为空").toJson());
- return;
- }
- if (navigationid == null || navigationid <= 0) {
- write(getResponseWarningMsgPackage("请先选择发布栏目").toJson());
- return;
- }
- GeneralDBAccess gdba = getGdbaInstance();
- WebsiteNavigation wn = getWebsiteNavigationById(gdba, navigationid);
- if (!isArticleTargetNavigation(wn)) {
- write(getResponseWarningMsgPackage("发布栏目必须选择可发布文章的栏目").toJson());
- return;
- }
- if (hasEnabledChildNavigation(gdba, navigationid)) {
- write(getResponseWarningMsgPackage("发布栏目必须选择最下级栏目,请继续向右选择最后一级栏目").toJson());
- return;
- }
- String editPath = WebEditorUtil.createHtmlFile(content);
- String runContent = converArticleContentHtmlLink(getWebRootPath() + editPath,
- space.apps.moudules.website.common.ConstVars.domain);
- String runPath = WebEditorUtil.createHtmlFile(runContent);
- String previewKey = java.util.UUID.randomUUID().toString().replace("-", "");
- setSessionAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + previewKey,
- buildPreviewInfo(runPath, wn, title, source, desc));
- Map<String, Object> retMap = new HashMap<String, Object>();
- retMap.put("url", "/apps?ark=website.article_preview_view&key=" + URLEncoder.encode(previewKey, "UTF-8"));
- write(getResponseSuccessDataPackage(retMap).toJsonWriteNonStringValueAsString());
- }
- /**
- * 输出文章正文临时预览内容。
- *
- * @throws Exception
- * @author SPACE
- */
- public void previewView() throws Exception {
- getResponse().setContentType("text/html;charset=UTF-8");
- String key = getParameter("key");
- if (StringUtil.isNull(key)) {
- writePreviewUnavailable();
- return;
- }
- Object previewObj = getSession().getAttribute(ARTICLE_PREVIEW_SESSION_PREFIX + key);
- String previewPath = getPreviewRunPath(previewObj);
- File previewFile = getSafePreviewFile(previewPath);
- if (previewFile == null) {
- writePreviewUnavailable();
- return;
- }
- if (previewObj instanceof Map) {
- renderArticlePreviewPage(previewObj, previewFile);
- return;
- }
- write(buildArticlePreviewHtml(null, null, FileUtil.readFile(previewFile.getPath())));
- }
- /**
- * 文章信息弹窗内容区 PC 预览(与三端预览 PC 端同源)。
- */
- public void infoPreviewView() throws Exception {
- getResponse().setContentType("text/html;charset=UTF-8");
- Long articleid = getParameterToLong("articleid");
- if (articleid == null || articleid <= 0) {
- writePreviewUnavailable();
- return;
- }
- GeneralDBAccess gdba = getGdbaInstance();
- Article article = new Article();
- article.setArticleid(articleid);
- gdba.selectById(article);
- Website website = new Website();
- website.setWebsiteid(article.getWebsiteid());
- gdba.selectById(website);
- WebsiteNavigation navigation = getWebsiteNavigationById(gdba, article.getNavigationid());
- String articleContent;
- try {
- articleContent = FileUtil.readFile(getWebRootPath() + article.getContent());
- } catch (Exception e) {
- writePreviewUnavailable();
- return;
- }
- write(buildArticleInfoPreviewHtml(article, website, navigation, articleContent));
- }
- private String buildArticleInfoPreviewHtml(Article article, Website website, WebsiteNavigation navigation,
- String articleContent) {
- Map<String, Object> previewInfo = new HashMap<String, Object>();
- previewInfo.put(PREVIEW_TITLE_KEY, article.getTitle());
- previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(article.getSource(), website.getName()));
- previewInfo.put(PREVIEW_RELEASE_TIME_KEY, formatArticleReleaseTime(article.getReleaseTime()));
- previewInfo.put(PREVIEW_NAVIGATION_ID_KEY,
- article.getNavigationid() == null ? "" : article.getNavigationid().toString());
- previewInfo.put(PREVIEW_WEBSITE_ID_KEY,
- article.getWebsiteid() == null ? "" : article.getWebsiteid().toString());
- return buildArticlePreviewHtml(previewInfo, navigation, website, articleContent);
- }
- private String formatArticleReleaseTime(Timestamp releaseTime) {
- if (releaseTime == null) {
- return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm");
- }
- try {
- String formatted = DateTimeUtil.formatDateYMdHms(releaseTime);
- return StringUtil.isNull(formatted) ? DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm") : formatted;
- } catch (ParseException e) {
- return DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm");
- }
- }
- private Map<String, Object> buildPreviewInfo(String runPath, WebsiteNavigation navigation, String title,
- String source, String desc) {
- Map<String, Object> previewInfo = new HashMap<String, Object>();
- previewInfo.put(PREVIEW_RUN_PATH_KEY, runPath);
- previewInfo.put(PREVIEW_TITLE_KEY, firstNotBlank(title, "正文预览"));
- previewInfo.put(PREVIEW_SOURCE_KEY, firstNotBlank(source, ""));
- previewInfo.put(PREVIEW_DESC_KEY, firstNotBlank(desc, ""));
- previewInfo.put(PREVIEW_NAVIGATION_ID_KEY,
- navigation == null || navigation.getNavigationid() == null ? "" : navigation.getNavigationid().toString());
- previewInfo.put(PREVIEW_WEBSITE_ID_KEY,
- navigation == null || navigation.getWebsiteid() == null ? "" : navigation.getWebsiteid().toString());
- return previewInfo;
- }
- @SuppressWarnings("rawtypes")
- private String getPreviewRunPath(Object previewObj) {
- if (previewObj instanceof Map) {
- Object runPath = ((Map) previewObj).get(PREVIEW_RUN_PATH_KEY);
- return runPath == null ? "" : runPath.toString();
- }
- return previewObj == null ? "" : previewObj.toString();
- }
- @SuppressWarnings("rawtypes")
- private void renderArticlePreviewPage(Object previewObj, File previewFile) throws Exception {
- Map previewInfo = (Map) previewObj;
- GeneralDBAccess gdba = getGdbaInstance();
- Long navigationId = parseLong(previewInfo.get(PREVIEW_NAVIGATION_ID_KEY));
- Long websiteId = parseLong(previewInfo.get(PREVIEW_WEBSITE_ID_KEY));
- WebsiteNavigation navigation = navigationId == null ? null : getWebsiteNavigationById(gdba, navigationId);
- if (navigation != null && navigation.getWebsiteid() != null) {
- websiteId = navigation.getWebsiteid();
- }
- Website website = websiteId == null ? null : WebsiteUtil.getWebsiteByID(gdba, websiteId);
- String articleContent = restorePreviewLazyImages(FileUtil.readFile(previewFile.getPath()));
- write(buildArticlePreviewHtml(previewInfo, navigation, website, articleContent));
- }
- private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, Website website,
- String articleContent) {
- String title = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_TITLE_KEY), "正文预览");
- String source = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_SOURCE_KEY),
- website == null ? "" : website.getName());
- String releaseTime = firstNotBlank(previewInfo == null ? null : previewInfo.get(PREVIEW_RELEASE_TIME_KEY),
- DateTimeUtil.getNowDate("yyyy-MM-dd HH:mm"));
- String content = restorePreviewLazyImages(firstNotBlank(articleContent, ""));
- StringBuilder html = new StringBuilder();
- html.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">")
- .append("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">")
- .append("<link rel=\"stylesheet\" href=\"/main/ffkj-portal/portal-source.css?v=20260703-article-image-fit-v2\">")
- .append("<link rel=\"stylesheet\" href=\"/apps/space/css/space.editor.css?v=20260703-article-image-fit-v2\">")
- .append("<style>")
- .append("html{height:100%;overflow:hidden;}")
- .append("body{margin:0;height:100%;overflow-x:hidden;overflow-y:auto;background:#f5f7fa;color:#1f2937;font-family:Arial,'Microsoft YaHei',sans-serif;}")
- .append(".preview-article{box-sizing:border-box;max-width:900px;margin:0 auto;padding:36px 32px;background:#fff;min-height:100%;}")
- .append(".preview-article.article-panel{padding:36px 32px!important;}")
- .append(".preview-article-header{margin:0 0 22px;padding:0 0 18px;border-bottom:3px solid #a40011;}")
- .append(".preview-article-title{margin:0;color:#a40011;font-size:30px;line-height:1.35;font-weight:700;letter-spacing:0;}")
- .append(".preview-article-meta{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:14px;color:#666;font-size:14px;line-height:1.5;}")
- .append(".preview-article-body{font-size:16px;line-height:1.9;color:#333;}")
- .append(".preview-article-body .ck-content,#jquery-lazyload-container.ck-content{width:100%!important;margin:0!important;padding:0!important;}")
- .append(".preview-article-body img,.article-body img,.preview-article-body .ck-content img,.article-body .ck-content img,.preview-article-body figure.image img,.article-body figure.image img,.preview-article-body .ck-content .image img,.article-body .ck-content .image img{display:block;width:100%!important;max-width:100%!important;height:auto!important;margin:18px 0!important;box-sizing:border-box;}")
- .append(".preview-article-body figure.image,.article-body figure.image,.preview-article-body figure:has(img),.article-body figure:has(img),.preview-article-body .ck-content .image,.article-body .ck-content .image,.preview-article-body .ck-content figure,.article-body .ck-content figure{display:block!important;width:100%!important;max-width:100%!important;margin:18px 0!important;padding:0!important;text-align:left!important;}")
- .append(".preview-article-body p:has(img),.preview-article-body div:has(img),.preview-article-body figure:has(img),")
- .append(".article-body p:has(img),.article-body div:has(img),.article-body figure:has(img),")
- .append(".preview-article-body .ck-content p:has(img),.preview-article-body .ck-content div:has(img),.article-body .ck-content p:has(img),.article-body .ck-content div:has(img){text-align:left!important;text-indent:0!important;}")
- .append(".preview-article-body video,.preview-article-body iframe,.preview-article-body object,.preview-article-body embed,.article-body video,.article-body iframe,.article-body object,.article-body embed{display:block;width:100%!important;max-width:100%!important;margin:18px 0!important;}")
- .append(".preview-article-body figure.space-editor-pdf-viewer{max-width:100%;}")
- .append(".preview-article-body iframe.space-editor-pdf-frame{width:100%;height:min(78vh,720px);min-height:480px;}")
- .append("@media (max-width: 700px){.preview-article{padding:24px 18px;}.preview-article-title{font-size:24px;}.preview-article-body iframe.space-editor-pdf-frame{min-height:420px;}}")
- .append("</style></head><body>")
- .append("<article class=\"preview-article article-panel school-article-panel\">")
- .append("<header class=\"preview-article-header article-header\">");
- html.append("<h1 class=\"preview-article-title\">").append(escapeHtml(title)).append("</h1>")
- .append("<div class=\"preview-article-meta\">")
- .append("<span>").append(escapeHtml(releaseTime)).append("</span>");
- if (!StringUtil.isNull(source)) {
- html.append("<span>来源:").append(escapeHtml(source)).append("</span>");
- }
- html.append("</div></header>")
- .append("<div class=\"preview-article-body article-body\" data-article-preview=\"true\">")
- .append(content)
- .append("</div></article>")
- .append("<script>(function(){var root=document.querySelector('.article-body,[data-article-preview]');if(!root){return;}function normalizeNode(node){if(!node){return;}node.style.setProperty('display','block','important');node.style.setProperty('width','100%','important');node.style.setProperty('max-width','100%','important');node.style.setProperty('margin','18px 0','important');node.style.setProperty('padding','0','important');node.style.setProperty('text-align','left','important');}root.querySelectorAll('.ck-content .image,figure.image,figure').forEach(function(fig){if(!fig.querySelector('img')){return;}normalizeNode(fig);});root.querySelectorAll('img').forEach(function(img){img.style.setProperty('display','block','important');img.style.setProperty('width','100%','important');img.style.setProperty('max-width','100%','important');img.style.setProperty('height','auto','important');img.style.setProperty('margin','18px 0','important');var parent=img.closest('p,div,figure,.image');if(parent){parent.style.setProperty('text-align','left','important');parent.style.setProperty('text-indent','0','important');}});})();</script>")
- .append("</body></html>");
- return html.toString();
- }
- private String buildArticlePreviewHtml(Map previewInfo, WebsiteNavigation navigation, String articleContent) {
- return buildArticlePreviewHtml(previewInfo, navigation, null, articleContent);
- }
- private String restorePreviewLazyImages(String articleContent) {
- if (StringUtil.isNull(articleContent)) {
- return articleContent;
- }
- Document doc = Jsoup.parseBodyFragment(normalizeLocalUploadResourceUrl(articleContent));
- Elements lazyImages = doc.select("img[data-original]");
- for (Element image : lazyImages) {
- if (StringUtil.isNull(image.attr("src"))) {
- image.attr("src", image.attr("data-original"));
- }
- }
- normalizePreviewArticleImages(doc);
- doc.select("script").remove();
- unwrapArticleContentContainer(doc);
- return doc.body().html();
- }
- private void unwrapArticleContentContainer(Document doc) {
- Elements wrappers = doc.select("#jquery-lazyload-container, div.ck-content");
- for (Element wrapper : wrappers) {
- wrapper.unwrap();
- }
- }
- private void normalizePreviewArticleImages(Document doc) {
- Elements figures = doc.select("figure.image, figure.image_resized, figure:has(img), .ck-content .image");
- for (Element figure : figures) {
- figure.removeAttr("width");
- figure.removeAttr("height");
- figure.attr("style", "display:block;width:100%;max-width:100%;margin:18px 0;text-align:left;");
- }
- Elements images = doc.select("img");
- for (Element image : images) {
- image.removeAttr("width");
- image.removeAttr("height");
- image.removeAttr("hspace");
- image.removeAttr("vspace");
- image.removeAttr("border");
- image.attr("style", "display:block;width:100%;max-width:100%;height:auto;margin:18px 0;box-sizing:border-box;");
- }
- Elements mediaBlocks = doc.select("p:has(img), div:has(img), figure:has(img)");
- for (Element block : mediaBlocks) {
- String style = block.attr("style");
- style = stripArticleImageStyleProperty(style, "width");
- style = stripArticleImageStyleProperty(style, "max-width");
- style = stripArticleImageStyleProperty(style, "margin");
- style = stripArticleImageStyleProperty(style, "text-align");
- style = stripArticleImageStyleProperty(style, "text-indent");
- block.attr("style", joinArticleImageStyle(style,
- "text-align:left;text-indent:0;"));
- }
- }
- private String stripArticleImageStyleProperty(String style, String property) {
- if (StringUtil.isNull(style) || StringUtil.isNull(property)) {
- return style == null ? "" : style;
- }
- return style.replaceAll("(?i)" + Pattern.quote(property) + "\\s*:[^;\"']*(;|$)", "$1").trim();
- }
- private String joinArticleImageStyle(String baseStyle, String appendStyle) {
- String normalizedBase = baseStyle == null ? "" : baseStyle.trim();
- if (normalizedBase.length() > 0 && !normalizedBase.endsWith(";")) {
- normalizedBase += ";";
- }
- return normalizedBase + appendStyle;
- }
- private String normalizeLocalUploadResourceUrl(String content) {
- if (StringUtil.isNull(content) || content.indexOf("/web/upload/") < 0) {
- return content;
- }
- return LOCAL_UPLOAD_ABSOLUTE_URL_PATTERN.matcher(content).replaceAll("$1");
- }
- private String escapeHtml(String value) {
- if (value == null) {
- return "";
- }
- return value.replace("&", "&").replace("<", "<").replace(">", ">")
- .replace("\"", """).replace("'", "'");
- }
- private Long parseLong(Object value) {
- if (value == null || StringUtil.isNull(value.toString())) {
- return null;
- }
- try {
- return Long.valueOf(value.toString());
- } catch (Exception e) {
- return null;
- }
- }
- private String firstNotBlank(Object value, String fallback) {
- if (value == null) {
- return fallback;
- }
- String text = value.toString().trim();
- return text.length() == 0 ? fallback : text;
- }
- private File getSafePreviewFile(String previewPath) throws Exception {
- if (StringUtil.isNull(previewPath)) {
- return null;
- }
- String normalizedPath = previewPath.replace("\\", "/");
- if (!normalizedPath.endsWith(".html")) {
- return null;
- }
- File webRoot = new File(getWebRootPath()).getCanonicalFile();
- File uploadRoot = new File(webRoot, "web/upload").getCanonicalFile();
- File previewFile = normalizedPath.startsWith("/")
- ? new File(webRoot, normalizedPath.substring(1)).getCanonicalFile()
- : new File(webRoot, normalizedPath).getCanonicalFile();
- if (!previewFile.getPath().startsWith(uploadRoot.getPath() + File.separator)) {
- return null;
- }
- return previewFile.isFile() ? previewFile : null;
- }
- private void writePreviewUnavailable() throws Exception {
- write("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>"
- + "body{margin:0;font-family:Arial,'Microsoft YaHei',sans-serif;background:#f5f7fa;color:#606266;}"
- + ".msg{padding:80px 20px;text-align:center;font-size:14px;}"
- + "</style></head><body><div class=\"msg\">预览内容不存在,请刷新预览后再查看。</div></body></html>");
- }
- // 测试的服务
- /**
- * 重置文章运行文件,主要是替换链接的域名,固定替换为 space.apps.moudules.website.common.ConstVars.domain
- *
- * @return
- * @throws Exception
- * @author 陈锋
- * @log 2020年10月19日
- */
- public String resetArticleRunHtmlLink() throws Exception {
- GeneralDBAccess gdba = getGdbaInstance();
- SqlCommandImpl sqlCmd = new SqlCommandImpl("select * from article ");
- @SuppressWarnings("unchecked")
- List<Article> articleList = gdba.selectAsList(sqlCmd, Article.class);
- String webPath = getWebRootPath();
- for (Article article : articleList) {
- File file = new File(webPath + article.getContent());
- if (".DS_Store".equals(file.getName())) {
- continue;
- }
- if (!file.isFile()) {
- continue;
- }
- String content = converArticleContentHtmlLink(file, space.apps.moudules.website.common.ConstVars.domain,
- webPath);
- FileUtil.writeFile(content, file.getPath());
- }
- ResponsePackage rp = getResponseSuccessPackage();
- setResponsePackage(rp);
- return DEFAULT_FORWARD;
- }
- /**
- * 转换文章内容 html 里的链接
- *
- * @param path
- * @param domain
- * @return
- * @throws Exception
- * @author 陈锋
- * @log 2020年10月16日
- */
- private String converArticleContentHtmlLink(File input, String domain, String webPath) throws Exception {
- Document doc = Jsoup.parse(input, "UTF-8", "");
- Elements srcEles = doc.select("img[src]");
- Elements originalEles = doc.select("img[data-original]");
- Elements mediaSrcEles = doc.select("iframe[src], embed[src], object[src]");
- Elements objectDataEles = doc.select("object[data]");
- Elements hrefEles = doc.select("a[href]");
- replaceAllHtmlLink(srcEles, "src", domain);
- replaceAllHtmlLink(originalEles, "data-original", domain);
- replaceAllHtmlLink(mediaSrcEles, "src", domain);
- replaceAllHtmlLink(objectDataEles, "data", domain);
- replaceAllHtmlLink(hrefEles, "href", domain);
- imgSrcConverLazyloadSrc(doc);
- normalizePreviewArticleImages(doc);
- String html = doc.select("body").eq(0).html();
- String articleTemplate = html;
- if (html.indexOf("jquery-lazyload-container") == -1) {
- articleTemplate = FileUtil.readFile(webPath + "/main/apps/template/article_issue_template.txt");
- articleTemplate = articleTemplate.replace("{article_content}", html);
- }
- return articleTemplate;
- }
- /**
- * 替换全部链接
- *
- * @param attrEles
- * @param attr
- * @param domain
- * @author 陈锋
- * @log 2020年10月19日
- */
- private void replaceAllHtmlLink(Elements attrEles, String attr, String domain) {
- for (Element ele : attrEles) {
- if (ele.tagName().equalsIgnoreCase("img")) {
- ele.removeAttr("width");
- ele.removeAttr("height");
- ele.removeAttr("style");
- ele.removeAttr("title");
- ele.removeAttr("alt");
- ele.removeAttr("onload");
- ele.removeAttr("border");
- ele.removeAttr("vspace");
- resetParentsPTagStyle(ele);
- }
- String attrValue = ele.attr(attr);
- if (StringUtil.isNull(attrValue)) {
- continue;
- }
- if (attrValue.startsWith("http://42.247.50.199")) {
- attrValue = attrValue.replace("http://42.247.50.199", "");
- } else {
- if (shouldKeepOriginalAttrValue(attrValue)) {
- continue;
- }
- }
- attrValue = FileUtil.replacePathSprit(attrValue);
- if (domain.endsWith("/") && attrValue.startsWith("/")) {
- attrValue = domain + attrValue.substring(1);
- } else {
- attrValue = domain + attrValue;
- }
- if ("href".equals(attr)) {
- ele.attr("target", "_blank");
- }
- ele.attr(attr, attrValue);
- }
- }
- /**
- * 只替换 img 标签上的 p 标签,p 标签加 style="text-align: center"
- *
- * @param imgEle
- * @author 陈锋
- * @log 2020年10月19日
- */
- private void resetParentsPTagStyle(Element imgEle) {
- Element parentEle = imgEle.parent();
- for (int i = 0; i < 6; i++) {
- if (parentEle == null) {
- return;
- }
- if (!parentEle.tagName().equals("p")) {
- parentEle = parentEle.parent();
- } else {
- parentEle.attr("style", "text-align: center");
- break;
- }
- }
- }
- @Override
- public boolean isNextServiceFlag() {
- String nsFlag = this.getRequest().getParameter("nextServiceFormFlag");
- return StringUtil.notNull(nsFlag) && nsFlag.equals("true");
- }
- }
|