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