DocumentController.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. package controllers
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "image/png"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/beego/beego/v2/client/orm"
  17. "github.com/beego/beego/v2/core/logs"
  18. "github.com/beego/beego/v2/server/web"
  19. "github.com/beego/i18n"
  20. "github.com/boombuler/barcode"
  21. "github.com/boombuler/barcode/qr"
  22. "github.com/mindoc-org/mindoc/conf"
  23. "github.com/mindoc-org/mindoc/models"
  24. "github.com/mindoc-org/mindoc/utils"
  25. "github.com/mindoc-org/mindoc/utils/cryptil"
  26. "github.com/mindoc-org/mindoc/utils/filetil"
  27. "github.com/mindoc-org/mindoc/utils/gopool"
  28. "github.com/mindoc-org/mindoc/utils/pagination"
  29. "github.com/russross/blackfriday/v2"
  30. )
  31. // DocumentController struct
  32. type DocumentController struct {
  33. BaseController
  34. }
  35. // 文档首页
  36. func (c *DocumentController) Index() {
  37. c.Prepare()
  38. identify := c.Ctx.Input.Param(":key")
  39. token := c.GetString("token")
  40. if identify == "" {
  41. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  42. }
  43. // 如果没有开启匿名访问则跳转到登录
  44. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  45. promptUserToLogIn(c)
  46. return
  47. }
  48. bookResult := c.isReadable(identify, token)
  49. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  50. selected := 0
  51. if bookResult.IsUseFirstDocument {
  52. doc, err := bookResult.FindFirstDocumentByBookId(bookResult.BookId)
  53. if err == nil {
  54. selected = doc.DocumentId
  55. c.Data["Title"] = doc.DocumentName
  56. c.Data["Content"] = template.HTML(doc.Release)
  57. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  58. c.Data["FoldSetting"] = "first"
  59. if bookResult.Editor == EditorCherryMarkdown {
  60. c.Data["MarkdownTheme"] = doc.MarkdownTheme
  61. }
  62. if bookResult.IsDisplayComment {
  63. // 获取评论、分页
  64. comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member)
  65. page := pagination.PageUtil(int(count), 1, conf.PageSize, comments)
  66. c.Data["Page"] = page
  67. }
  68. }
  69. } else {
  70. c.Data["Title"] = i18n.Tr(c.Lang, "blog.summary")
  71. c.Data["Content"] = template.HTML(blackfriday.Run([]byte(bookResult.Description)))
  72. c.Data["FoldSetting"] = "closed"
  73. }
  74. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, selected)
  75. if err != nil {
  76. if err == orm.ErrNoRows {
  77. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.no_doc_in_cur_proj"))
  78. } else {
  79. logs.Error("生成项目文档树时出错 -> ", err)
  80. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.build_doc_tree_error"))
  81. }
  82. }
  83. c.Data["IS_DOCUMENT_INDEX"] = true
  84. c.Data["Model"] = bookResult
  85. c.Data["Result"] = template.HTML(tree)
  86. }
  87. // CheckPassword : Handles password verification for private documents,
  88. // and front-end requests are made through Ajax.
  89. func (c *DocumentController) CheckPassword() {
  90. identify := c.Ctx.Input.Param(":key")
  91. password := c.GetString("bPassword")
  92. if identify == "" || password == "" {
  93. c.JsonResult(http.StatusBadRequest, i18n.Tr(c.Lang, "message.param_error"))
  94. }
  95. // You have not logged in and need to log in again.
  96. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  97. logs.Info("You have not logged in and need to log in again(SessionId: %s).",
  98. c.CruSession.SessionID(context.TODO()))
  99. c.JsonResult(6000, i18n.Tr(c.Lang, "message.need_relogin"))
  100. return
  101. }
  102. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  103. if err != nil {
  104. logs.Error(err)
  105. c.JsonResult(500, i18n.Tr(c.Lang, "message.item_not_exist"))
  106. }
  107. if book.BookPassword != password {
  108. c.JsonResult(5001, i18n.Tr(c.Lang, "message.wrong_password"))
  109. } else {
  110. c.SetSession(identify, password)
  111. c.JsonResult(0, "OK")
  112. }
  113. }
  114. // 阅读文档
  115. func (c *DocumentController) Read() {
  116. identify := c.Ctx.Input.Param(":key")
  117. token := c.GetString("token")
  118. id := c.GetString(":id")
  119. if identify == "" || id == "" {
  120. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  121. }
  122. // 如果没有开启匿名访问则跳转到登录
  123. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  124. promptUserToLogIn(c)
  125. return
  126. }
  127. bookResult := c.isReadable(identify, token)
  128. c.TplName = fmt.Sprintf("document/%s_read.tpl", bookResult.Theme)
  129. doc := models.NewDocument()
  130. if docId, err := strconv.Atoi(id); err == nil {
  131. doc, err = doc.FromCacheById(docId)
  132. if err != nil || doc == nil {
  133. logs.Error("从缓存中读取文档时失败 ->", err)
  134. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  135. return
  136. }
  137. } else {
  138. doc, err = doc.FromCacheByIdentify(id, bookResult.BookId)
  139. if err != nil || doc == nil {
  140. if err == orm.ErrNoRows {
  141. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  142. } else {
  143. logs.Error("从数据库查询文档时出错 ->", err)
  144. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.unknown_exception"))
  145. }
  146. return
  147. }
  148. }
  149. if doc.BookId != bookResult.BookId {
  150. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  151. }
  152. doc.Lang = c.Lang
  153. doc.Processor()
  154. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  155. if err == nil {
  156. doc.AttachList = attach
  157. }
  158. doc.IncrViewCount(doc.DocumentId)
  159. doc.ViewCount = doc.ViewCount + 1
  160. doc.PutToCache()
  161. if c.IsAjax() {
  162. var data struct {
  163. DocId int `json:"doc_id"`
  164. DocIdentify string `json:"doc_identify"`
  165. DocTitle string `json:"doc_title"`
  166. Body string `json:"body"`
  167. Title string `json:"title"`
  168. Version int64 `json:"version"`
  169. ViewCount int `json:"view_count"`
  170. MarkdownTheme string `json:"markdown_theme"`
  171. IsMarkdown bool `json:"is_markdown"`
  172. }
  173. data.DocId = doc.DocumentId
  174. data.DocIdentify = doc.Identify
  175. data.DocTitle = doc.DocumentName
  176. data.Body = doc.Release
  177. data.Title = doc.DocumentName + " - Powered by MinDoc"
  178. data.Version = doc.Version
  179. data.ViewCount = doc.ViewCount
  180. data.MarkdownTheme = doc.MarkdownTheme
  181. if bookResult.Editor == EditorCherryMarkdown {
  182. data.IsMarkdown = true
  183. }
  184. c.JsonResult(0, "ok", data)
  185. } else {
  186. c.Data["DocumentId"] = doc.DocumentId
  187. c.Data["DocIdentify"] = doc.Identify
  188. if bookResult.IsDisplayComment {
  189. // 获取评论、分页
  190. comments, count, _ := models.NewComment().QueryCommentByDocumentId(doc.DocumentId, 1, conf.PageSize, c.Member)
  191. page := pagination.PageUtil(int(count), 1, conf.PageSize, comments)
  192. c.Data["Page"] = page
  193. }
  194. }
  195. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
  196. if err != nil && err != orm.ErrNoRows {
  197. logs.Error("生成项目文档树时出错 ->", err)
  198. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.build_doc_tree_error"))
  199. }
  200. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  201. c.Data["Model"] = bookResult
  202. c.Data["Result"] = template.HTML(tree)
  203. c.Data["Title"] = doc.DocumentName
  204. c.Data["Content"] = template.HTML(doc.Release)
  205. c.Data["ViewCount"] = doc.ViewCount
  206. c.Data["FoldSetting"] = "closed"
  207. if bookResult.Editor == EditorCherryMarkdown {
  208. c.Data["MarkdownTheme"] = doc.MarkdownTheme
  209. }
  210. if doc.IsOpen == 1 {
  211. c.Data["FoldSetting"] = "open"
  212. } else if doc.IsOpen == 2 {
  213. c.Data["FoldSetting"] = "empty"
  214. }
  215. }
  216. // 编辑文档
  217. func (c *DocumentController) Edit() {
  218. c.Prepare()
  219. identify := c.Ctx.Input.Param(":key")
  220. if identify == "" {
  221. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.project_id_error"))
  222. }
  223. bookResult := models.NewBookResult()
  224. var err error
  225. // 如果是管理者,则不判断权限
  226. if c.Member.IsAdministrator() {
  227. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  228. if err != nil {
  229. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  230. }
  231. bookResult = models.NewBookResult().ToBookResult(*book)
  232. } else {
  233. bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  234. if err != nil {
  235. if err == orm.ErrNoRows || err == models.ErrPermissionDenied {
  236. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  237. } else {
  238. logs.Error("查询项目时出错 -> ", err)
  239. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  240. }
  241. return
  242. }
  243. if bookResult.RoleId == conf.BookObserver {
  244. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  245. }
  246. }
  247. c.TplName = fmt.Sprintf("document/%s_edit_template.tpl", bookResult.Editor)
  248. c.Data["Model"] = bookResult
  249. r, _ := json.Marshal(bookResult)
  250. c.Data["ModelResult"] = template.JS(string(r))
  251. c.Data["Result"] = template.JS("[]")
  252. trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  253. if err != nil {
  254. logs.Error("FindDocumentTree => ", err)
  255. } else {
  256. if len(trees) > 0 {
  257. if jtree, err := json.Marshal(trees); err == nil {
  258. c.Data["Result"] = template.JS(string(jtree))
  259. }
  260. } else {
  261. c.Data["Result"] = template.JS("[]")
  262. }
  263. }
  264. c.Data["BaiDuMapKey"] = web.AppConfig.DefaultString("baidumapkey", "")
  265. if conf.GetUploadFileSize() > 0 {
  266. c.Data["UploadFileSize"] = conf.GetUploadFileSize()
  267. } else {
  268. c.Data["UploadFileSize"] = "undefined"
  269. }
  270. }
  271. // 创建一个文档
  272. func (c *DocumentController) Create() {
  273. identify := c.GetString("identify")
  274. docIdentify := c.GetString("doc_identify")
  275. docName := c.GetString("doc_name")
  276. parentId, _ := c.GetInt("parent_id", 0)
  277. docId, _ := c.GetInt("doc_id", 0)
  278. isOpen, _ := c.GetInt("is_open", 0)
  279. if identify == "" {
  280. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  281. }
  282. if docName == "" {
  283. c.JsonResult(6004, i18n.Tr(c.Lang, "message.doc_name_empty"))
  284. }
  285. bookId := 0
  286. // 如果是超级管理员则不判断权限
  287. if c.Member.IsAdministrator() {
  288. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  289. if err != nil {
  290. logs.Error(err)
  291. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_existed_or_no_permit"))
  292. }
  293. bookId = book.BookId
  294. } else {
  295. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  296. if err != nil || bookResult.RoleId == conf.BookObserver {
  297. logs.Error("FindByIdentify => ", err)
  298. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_existed_or_no_permit"))
  299. }
  300. bookId = bookResult.BookId
  301. }
  302. if docIdentify != "" {
  303. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
  304. c.JsonResult(6003, i18n.Tr(c.Lang, "message.project_id_tips"))
  305. }
  306. d, _ := models.NewDocument().FindByIdentityFirst(docIdentify, bookId)
  307. if d.DocumentId > 0 && d.DocumentId != docId {
  308. c.JsonResult(6006, i18n.Tr(c.Lang, "message.project_id_existed"))
  309. }
  310. }
  311. if parentId > 0 {
  312. doc, err := models.NewDocument().Find(parentId)
  313. if err != nil || doc.BookId != bookId {
  314. c.JsonResult(6003, i18n.Tr(c.Lang, "message.parent_id_not_existed"))
  315. }
  316. }
  317. document, _ := models.NewDocument().Find(docId)
  318. document.MemberId = c.Member.MemberId
  319. document.BookId = bookId
  320. document.Identify = docIdentify
  321. document.Version = time.Now().Unix()
  322. document.DocumentName = docName
  323. document.ParentId = parentId
  324. if isOpen == 1 {
  325. document.IsOpen = 1
  326. } else if isOpen == 2 {
  327. document.IsOpen = 2
  328. } else {
  329. document.IsOpen = 0
  330. }
  331. if err := document.InsertOrUpdate(); err != nil {
  332. logs.Error("添加或更新文档时出错 -> ", err)
  333. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  334. } else {
  335. c.JsonResult(0, "ok", document)
  336. }
  337. }
  338. // 上传附件或图片
  339. func (c *DocumentController) Upload() {
  340. identify := c.GetString("identify")
  341. docId, _ := c.GetInt("doc_id")
  342. isAttach := true
  343. if identify == "" {
  344. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  345. }
  346. name := "editormd-file-file"
  347. file, moreFile, err := c.GetFile(name)
  348. if err == http.ErrMissingFile || moreFile == nil {
  349. name = "editormd-image-file"
  350. file, moreFile, err = c.GetFile(name)
  351. if err == http.ErrMissingFile || moreFile == nil {
  352. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_empty"))
  353. return
  354. }
  355. }
  356. if err != nil {
  357. c.JsonResult(6002, err.Error())
  358. }
  359. defer file.Close()
  360. type Size interface {
  361. Size() int64
  362. }
  363. if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
  364. c.JsonResult(6009, i18n.Tr(c.Lang, "message.upload_file_size_limit"))
  365. }
  366. ext := filepath.Ext(moreFile.Filename)
  367. //文件必须带有后缀名
  368. if ext == "" {
  369. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  370. }
  371. //如果文件类型设置为 * 标识不限制文件类型
  372. if conf.IsAllowUploadFileExt(ext) == false {
  373. c.JsonResult(6004, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  374. }
  375. bookId := 0
  376. // 如果是超级管理员,则不判断权限
  377. if c.Member.IsAdministrator() {
  378. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  379. if err != nil {
  380. c.JsonResult(6006, i18n.Tr(c.Lang, "message.doc_not_exist_or_no_permit"))
  381. }
  382. bookId = book.BookId
  383. } else {
  384. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  385. if err != nil {
  386. logs.Error("DocumentController.Edit => ", err)
  387. if err == orm.ErrNoRows {
  388. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  389. }
  390. c.JsonResult(6001, err.Error())
  391. }
  392. // 如果没有编辑权限
  393. if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  394. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  395. }
  396. bookId = book.BookId
  397. }
  398. if docId > 0 {
  399. doc, err := models.NewDocument().Find(docId)
  400. if err != nil {
  401. c.JsonResult(6007, i18n.Tr(c.Lang, "message.doc_not_exist"))
  402. }
  403. if doc.BookId != bookId {
  404. c.JsonResult(6008, i18n.Tr(c.Lang, "message.doc_not_belong_project"))
  405. }
  406. }
  407. fileName := "m_" + cryptil.UniqueId() + "_r"
  408. filePath := filepath.Join(conf.WorkingDirectory, "uploads", identify)
  409. //将图片和文件分开存放
  410. if filetil.IsImageExt(moreFile.Filename) {
  411. filePath = filepath.Join(filePath, "images", fileName+ext)
  412. } else {
  413. filePath = filepath.Join(filePath, "files", fileName+ext)
  414. }
  415. path := filepath.Dir(filePath)
  416. _ = os.MkdirAll(path, os.ModePerm)
  417. err = c.SaveToFile(name, filePath)
  418. if err != nil {
  419. logs.Error("保存文件失败 -> ", err)
  420. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  421. }
  422. attachment := models.NewAttachment()
  423. attachment.BookId = bookId
  424. attachment.FileName = moreFile.Filename
  425. attachment.CreateAt = c.Member.MemberId
  426. attachment.FileExt = ext
  427. attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
  428. attachment.DocumentId = docId
  429. if fileInfo, err := os.Stat(filePath); err == nil {
  430. attachment.FileSize = float64(fileInfo.Size())
  431. }
  432. if docId > 0 {
  433. attachment.DocumentId = docId
  434. }
  435. if filetil.IsImageExt(moreFile.Filename) {
  436. attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  437. if strings.HasPrefix(attachment.HttpPath, "//") {
  438. attachment.HttpPath = conf.URLForWithCdnImage(string(attachment.HttpPath[1:]))
  439. }
  440. isAttach = false
  441. }
  442. err = attachment.Insert()
  443. if err != nil {
  444. os.Remove(filePath)
  445. logs.Error("文件保存失败 ->", err)
  446. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  447. }
  448. if attachment.HttpPath == "" {
  449. attachment.HttpPath = conf.URLForNotHost("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
  450. if err := attachment.Update(); err != nil {
  451. logs.Error("保存文件失败 ->", err)
  452. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  453. }
  454. }
  455. result := map[string]interface{}{
  456. "errcode": 0,
  457. "success": 1,
  458. "message": "ok",
  459. "url": attachment.HttpPath,
  460. "alt": attachment.FileName,
  461. "is_attach": isAttach,
  462. "attach": attachment,
  463. }
  464. c.Ctx.Output.JSON(result, true, false)
  465. c.StopRun()
  466. }
  467. // 下载附件
  468. func (c *DocumentController) DownloadAttachment() {
  469. c.Prepare()
  470. identify := c.Ctx.Input.Param(":key")
  471. attachId, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  472. token := c.GetString("token")
  473. memberId := 0
  474. if c.Member != nil {
  475. memberId = c.Member.MemberId
  476. }
  477. bookId := 0
  478. // 判断用户是否参与了项目
  479. bookResult, err := models.NewBookResult().FindByIdentify(identify, memberId)
  480. if err != nil {
  481. // 判断项目公开状态
  482. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  483. if err != nil {
  484. if err == orm.ErrNoRows {
  485. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  486. } else {
  487. logs.Error("查找项目时出错 ->", err)
  488. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  489. }
  490. }
  491. // 如果不是超级管理员则判断权限
  492. if c.Member == nil || c.Member.Role != conf.MemberSuperRole {
  493. // 如果项目是私有的,并且 token 不正确
  494. if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
  495. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  496. }
  497. }
  498. bookId = book.BookId
  499. } else {
  500. bookId = bookResult.BookId
  501. }
  502. // 查找附件
  503. attachment, err := models.NewAttachment().Find(attachId)
  504. if err != nil {
  505. logs.Error("查找附件时出错 -> ", err)
  506. if err == orm.ErrNoRows {
  507. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  508. } else {
  509. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  510. }
  511. }
  512. if attachment.BookId != bookId {
  513. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  514. }
  515. c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
  516. c.StopRun()
  517. }
  518. // 删除附件
  519. func (c *DocumentController) RemoveAttachment() {
  520. c.Prepare()
  521. attachId, _ := c.GetInt("attach_id")
  522. if attachId <= 0 {
  523. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  524. }
  525. attach, err := models.NewAttachment().Find(attachId)
  526. if err != nil {
  527. logs.Error(err)
  528. c.JsonResult(6002, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  529. }
  530. document, err := models.NewDocument().Find(attach.DocumentId)
  531. if err != nil {
  532. logs.Error(err)
  533. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  534. }
  535. if c.Member.Role != conf.MemberSuperRole {
  536. rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
  537. if err != nil {
  538. logs.Error(err)
  539. c.JsonResult(6004, i18n.Tr(c.Lang, "message.no_permission"))
  540. }
  541. if rel.RoleId == conf.BookObserver {
  542. c.JsonResult(6004, i18n.Tr(c.Lang, "message.no_permission"))
  543. }
  544. }
  545. err = attach.Delete()
  546. if err != nil {
  547. logs.Error(err)
  548. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  549. }
  550. os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
  551. c.JsonResult(0, "ok", attach)
  552. }
  553. // 删除文档
  554. func (c *DocumentController) Delete() {
  555. c.Prepare()
  556. identify := c.GetString("identify")
  557. docId, err := c.GetInt("doc_id", 0)
  558. bookId := 0
  559. // 如果是超级管理员则忽略权限判断
  560. if c.Member.IsAdministrator() {
  561. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  562. if err != nil {
  563. logs.Error("FindByIdentify => ", err)
  564. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  565. }
  566. bookId = book.BookId
  567. } else {
  568. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  569. if err != nil || bookResult.RoleId == conf.BookObserver {
  570. logs.Error("FindByIdentify => ", err)
  571. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  572. }
  573. bookId = bookResult.BookId
  574. }
  575. if docId <= 0 {
  576. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  577. }
  578. doc, err := models.NewDocument().Find(docId)
  579. if err != nil {
  580. logs.Error("Delete => ", err)
  581. c.JsonResult(6003, i18n.Tr(c.Lang, "message.failed"))
  582. }
  583. // 如果文档所属项目错误
  584. if doc.BookId != bookId {
  585. c.JsonResult(6004, i18n.Tr(c.Lang, "message.param_error"))
  586. }
  587. // 递归删除项目下的文档以及子文档
  588. err = doc.RecursiveDocument(doc.DocumentId)
  589. if err != nil {
  590. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  591. }
  592. // 重置文档数量统计
  593. models.NewBook().ResetDocumentNumber(doc.BookId)
  594. c.JsonResult(0, "ok")
  595. }
  596. // 获取文档内容
  597. func (c *DocumentController) Content() {
  598. c.Prepare()
  599. identify := c.Ctx.Input.Param(":key")
  600. docId, err := c.GetInt("doc_id")
  601. if err != nil {
  602. docId, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  603. }
  604. bookId := 0
  605. autoRelease := false
  606. // 如果是超级管理员,则忽略权限
  607. if c.Member.IsAdministrator() {
  608. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  609. if err != nil || book == nil {
  610. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  611. return
  612. }
  613. bookId = book.BookId
  614. autoRelease = book.AutoRelease == 1
  615. } else {
  616. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  617. if err != nil || bookResult.RoleId == conf.BookObserver {
  618. logs.Error("项目不存在或权限不足 -> ", err)
  619. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  620. }
  621. bookId = bookResult.BookId
  622. autoRelease = bookResult.AutoRelease
  623. }
  624. if docId <= 0 {
  625. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  626. }
  627. if c.Ctx.Input.IsPost() {
  628. markdown := strings.TrimSpace(c.GetString("markdown", ""))
  629. content := c.GetString("html")
  630. markdownTheme := c.GetString("markdown_theme", "theme__light")
  631. version, _ := c.GetInt64("version", 0)
  632. isCover := c.GetString("cover")
  633. doc, err := models.NewDocument().Find(docId)
  634. if err != nil || doc == nil {
  635. c.JsonResult(6003, i18n.Tr(c.Lang, "message.read_file_error"))
  636. return
  637. }
  638. if doc.BookId != bookId {
  639. c.JsonResult(6004, i18n.Tr(c.Lang, "message.dock_not_belong_project"))
  640. }
  641. if doc.Version != version && !strings.EqualFold(isCover, "yes") {
  642. logs.Info("%d|", version, doc.Version)
  643. c.JsonResult(6005, i18n.Tr(c.Lang, "message.confirm_override_doc"))
  644. }
  645. history := models.NewDocumentHistory()
  646. history.DocumentId = docId
  647. history.Content = doc.Content
  648. history.Markdown = doc.Markdown
  649. history.DocumentName = doc.DocumentName
  650. history.ModifyAt = c.Member.MemberId
  651. history.MemberId = doc.MemberId
  652. history.ParentId = doc.ParentId
  653. history.Version = time.Now().Unix()
  654. history.Action = "modify"
  655. history.ActionName = i18n.Tr(c.Lang, "doc.modify_doc")
  656. if markdown == "" && content != "" {
  657. doc.Markdown = content
  658. } else {
  659. doc.Markdown = markdown
  660. doc.MarkdownTheme = markdownTheme
  661. }
  662. doc.Version = time.Now().Unix()
  663. doc.Content = content
  664. doc.ModifyAt = c.Member.MemberId
  665. if err := doc.InsertOrUpdate(); err != nil {
  666. logs.Error("InsertOrUpdate => ", err)
  667. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  668. }
  669. // 如果启用了文档历史,则添加历史文档
  670. ///如果两次保存的MD5值不同则保存为历史,否则忽略
  671. go func(history *models.DocumentHistory) {
  672. if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) {
  673. _, err = history.InsertOrUpdate()
  674. if err != nil {
  675. logs.Error("DocumentHistory InsertOrUpdate => ", err)
  676. }
  677. }
  678. }(history)
  679. //如果启用了自动发布
  680. if autoRelease {
  681. go func() {
  682. doc.Lang = c.Lang
  683. err := doc.ReleaseContent()
  684. if err == nil {
  685. logs.Informational(i18n.Tr(c.Lang, "message.doc_auto_published")+"-> document_id=%d;document_name=%s", doc.DocumentId, doc.DocumentName)
  686. }
  687. }()
  688. }
  689. c.JsonResult(0, "ok", doc)
  690. }
  691. doc, err := models.NewDocument().Find(docId)
  692. if err != nil {
  693. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  694. return
  695. }
  696. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  697. if err == nil {
  698. doc.AttachList = attach
  699. }
  700. c.JsonResult(0, "ok", doc)
  701. }
  702. // Export 导出
  703. func (c *DocumentController) Export() {
  704. c.Prepare()
  705. identify := c.Ctx.Input.Param(":key")
  706. if identify == "" {
  707. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.param_error"))
  708. }
  709. output := c.GetString("output")
  710. token := c.GetString("token")
  711. // 如果没有开启匿名访问则跳转到登录
  712. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  713. promptUserToLogIn(c)
  714. return
  715. }
  716. if !conf.GetEnableExport() {
  717. c.ShowErrorPage(500, i18n.Tr(c.Lang, "export_func_disable"))
  718. }
  719. bookResult := models.NewBookResult()
  720. if c.Member != nil && c.Member.IsAdministrator() {
  721. book, err := models.NewBook().FindByIdentify(identify)
  722. if err != nil {
  723. if err == orm.ErrNoRows {
  724. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  725. } else {
  726. logs.Error("查找项目时出错 ->", err)
  727. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  728. }
  729. }
  730. bookResult = models.NewBookResult().ToBookResult(*book)
  731. } else {
  732. bookResult = c.isReadable(identify, token)
  733. }
  734. if !bookResult.IsDownload {
  735. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.cur_project_export_func_disable"))
  736. }
  737. if !strings.HasPrefix(bookResult.Cover, "http:://") && !strings.HasPrefix(bookResult.Cover, "https:://") {
  738. bookResult.Cover = conf.URLForWithCdnImage(bookResult.Cover)
  739. }
  740. if output == Markdown {
  741. if bookResult.Editor != EditorMarkdown && bookResult.Editor != EditorCherryMarkdown {
  742. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.cur_project_not_support_md"))
  743. }
  744. p, err := bookResult.ExportMarkdown(c.CruSession.SessionID(context.TODO()))
  745. if err != nil {
  746. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.failed"))
  747. }
  748. c.Ctx.Output.Download(p, bookResult.BookName+".zip")
  749. c.StopRun()
  750. return
  751. }
  752. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookResult.BookId))
  753. pdfpath := filepath.Join(outputPath, "book.pdf")
  754. epubpath := filepath.Join(outputPath, "book.epub")
  755. mobipath := filepath.Join(outputPath, "book.mobi")
  756. docxpath := filepath.Join(outputPath, "book.docx")
  757. if output == "pdf" && filetil.FileExists(pdfpath) {
  758. c.Ctx.Output.Download(pdfpath, bookResult.BookName+".pdf")
  759. c.Abort("200")
  760. } else if output == "epub" && filetil.FileExists(epubpath) {
  761. c.Ctx.Output.Download(epubpath, bookResult.BookName+".epub")
  762. c.Abort("200")
  763. } else if output == "mobi" && filetil.FileExists(mobipath) {
  764. c.Ctx.Output.Download(mobipath, bookResult.BookName+".mobi")
  765. c.Abort("200")
  766. } else if output == "docx" && filetil.FileExists(docxpath) {
  767. c.Ctx.Output.Download(docxpath, bookResult.BookName+".docx")
  768. c.Abort("200")
  769. } else if output == "pdf" || output == "epub" || output == "docx" || output == "mobi" {
  770. if err := models.BackgroundConvert(c.CruSession.SessionID(context.TODO()), bookResult); err != nil && err != gopool.ErrHandlerIsExist {
  771. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.export_failed"))
  772. }
  773. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.file_converting"))
  774. } else {
  775. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.unsupport_file_type"))
  776. }
  777. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.no_exportable_file"))
  778. }
  779. // 生成项目访问的二维码
  780. func (c *DocumentController) QrCode() {
  781. c.Prepare()
  782. identify := c.GetString(":key")
  783. book, err := models.NewBook().FindByIdentify(identify)
  784. if err != nil || book.BookId <= 0 {
  785. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  786. }
  787. uri := conf.URLFor("DocumentController.Index", ":key", identify)
  788. code, err := qr.Encode(uri, qr.L, qr.Unicode)
  789. if err != nil {
  790. logs.Error("生成二维码失败 ->", err)
  791. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  792. }
  793. code, err = barcode.Scale(code, 150, 150)
  794. if err != nil {
  795. logs.Error("生成二维码失败 ->", err)
  796. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  797. }
  798. c.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
  799. // imgpath := filepath.Join("cache","qrcode",identify + ".png")
  800. err = png.Encode(c.Ctx.ResponseWriter, code)
  801. if err != nil {
  802. logs.Error("生成二维码失败 ->", err)
  803. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  804. }
  805. }
  806. // 项目内搜索
  807. func (c *DocumentController) Search() {
  808. c.Prepare()
  809. identify := c.Ctx.Input.Param(":key")
  810. token := c.GetString("token")
  811. keyword := strings.TrimSpace(c.GetString("keyword"))
  812. if identify == "" {
  813. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  814. }
  815. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  816. promptUserToLogIn(c)
  817. return
  818. }
  819. bookResult := c.isReadable(identify, token)
  820. docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId)
  821. if err != nil {
  822. logs.Error(err)
  823. c.JsonResult(6002, i18n.Tr(c.Lang, "message.search_result_error"))
  824. }
  825. if len(docs) < 0 {
  826. c.JsonResult(404, i18n.Tr(c.Lang, "message.no_data"))
  827. }
  828. for _, doc := range docs {
  829. doc.BookId = bookResult.BookId
  830. doc.BookName = bookResult.BookName
  831. doc.Description = bookResult.Description
  832. doc.BookIdentify = bookResult.Identify
  833. }
  834. c.JsonResult(0, "ok", docs)
  835. }
  836. // 文档历史列表
  837. func (c *DocumentController) History() {
  838. c.Prepare()
  839. c.TplName = "document/history.tpl"
  840. identify := c.GetString("identify")
  841. docId, err := c.GetInt("doc_id", 0)
  842. pageIndex, _ := c.GetInt("page", 1)
  843. bookId := 0
  844. // 如果是超级管理员则忽略权限判断
  845. if c.Member.IsAdministrator() {
  846. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  847. if err != nil {
  848. logs.Error("查找项目失败 ->", err)
  849. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit")
  850. return
  851. }
  852. bookId = book.BookId
  853. c.Data["Model"] = book
  854. } else {
  855. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  856. if err != nil || bookResult.RoleId == conf.BookObserver {
  857. logs.Error("查找项目失败 ->", err)
  858. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit")
  859. return
  860. }
  861. bookId = bookResult.BookId
  862. c.Data["Model"] = bookResult
  863. }
  864. if docId <= 0 {
  865. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.param_error")
  866. return
  867. }
  868. doc, err := models.NewDocument().Find(docId)
  869. if err != nil {
  870. logs.Error("Delete => ", err)
  871. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.get_doc_his_failed")
  872. return
  873. }
  874. // 如果文档所属项目错误
  875. if doc.BookId != bookId {
  876. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.param_error")
  877. return
  878. }
  879. histories, totalCount, err := models.NewDocumentHistory().FindToPager(docId, pageIndex, conf.PageSize)
  880. if err != nil {
  881. logs.Error("分页查找文档历史失败 ->", err)
  882. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.get_doc_his_failed")
  883. return
  884. }
  885. c.Data["List"] = histories
  886. c.Data["PageHtml"] = ""
  887. c.Data["Document"] = doc
  888. if totalCount > 0 {
  889. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  890. c.Data["PageHtml"] = pager.HtmlPages()
  891. }
  892. }
  893. func (c *DocumentController) DeleteHistory() {
  894. c.Prepare()
  895. c.TplName = "document/history.tpl"
  896. identify := c.GetString("identify")
  897. docId, err := c.GetInt("doc_id", 0)
  898. historyId, _ := c.GetInt("history_id", 0)
  899. if historyId <= 0 {
  900. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  901. }
  902. bookId := 0
  903. // 如果是超级管理员则忽略权限判断
  904. if c.Member.IsAdministrator() {
  905. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  906. if err != nil {
  907. logs.Error("查找项目失败 ->", err)
  908. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  909. }
  910. bookId = book.BookId
  911. } else {
  912. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  913. if err != nil || bookResult.RoleId == conf.BookObserver {
  914. logs.Error("查找项目失败 ->", err)
  915. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  916. }
  917. bookId = bookResult.BookId
  918. }
  919. if docId <= 0 {
  920. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  921. }
  922. doc, err := models.NewDocument().Find(docId)
  923. if err != nil {
  924. logs.Error("Delete => ", err)
  925. c.JsonResult(6001, i18n.Tr(c.Lang, "message.get_doc_his_failed"))
  926. }
  927. // 如果文档所属项目错误
  928. if doc.BookId != bookId {
  929. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  930. }
  931. err = models.NewDocumentHistory().Delete(historyId, docId)
  932. if err != nil {
  933. logs.Error(err)
  934. c.JsonResult(6002, i18n.Tr(c.Lang, "message.failed"))
  935. }
  936. c.JsonResult(0, "ok")
  937. }
  938. // 通过文档历史恢复文档
  939. func (c *DocumentController) RestoreHistory() {
  940. c.Prepare()
  941. c.TplName = "document/history.tpl"
  942. identify := c.GetString("identify")
  943. docId, err := c.GetInt("doc_id", 0)
  944. historyId, _ := c.GetInt("history_id", 0)
  945. if historyId <= 0 {
  946. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  947. }
  948. bookId := 0
  949. // 如果是超级管理员则忽略权限判断
  950. if c.Member.IsAdministrator() {
  951. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  952. if err != nil {
  953. logs.Error("FindByIdentify => ", err)
  954. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  955. }
  956. bookId = book.BookId
  957. } else {
  958. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  959. if err != nil || bookResult.RoleId == conf.BookObserver {
  960. logs.Error("FindByIdentify => ", err)
  961. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  962. }
  963. bookId = bookResult.BookId
  964. }
  965. if docId <= 0 {
  966. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  967. }
  968. doc, err := models.NewDocument().Find(docId)
  969. if err != nil {
  970. logs.Error("Delete => ", err)
  971. c.JsonResult(6001, i18n.Tr(c.Lang, "message.get_doc_his_failed"))
  972. }
  973. // 如果文档所属项目错误
  974. if doc.BookId != bookId {
  975. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  976. }
  977. err = models.NewDocumentHistory().Restore(historyId, docId, c.Member.MemberId)
  978. if err != nil {
  979. logs.Error(err)
  980. c.JsonResult(6002, i18n.Tr(c.Lang, "message.failed"))
  981. }
  982. c.JsonResult(0, "ok", doc)
  983. }
  984. func (c *DocumentController) Compare() {
  985. c.Prepare()
  986. c.TplName = "document/compare.tpl"
  987. historyId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  988. identify := c.Ctx.Input.Param(":key")
  989. bookId := 0
  990. editor := EditorMarkdown
  991. // 如果是超级管理员则忽略权限判断
  992. if c.Member.IsAdministrator() {
  993. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  994. if err != nil {
  995. logs.Error("DocumentController.Compare => ", err)
  996. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  997. return
  998. }
  999. bookId = book.BookId
  1000. c.Data["Model"] = book
  1001. editor = book.Editor
  1002. } else {
  1003. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  1004. if err != nil || bookResult.RoleId == conf.BookObserver {
  1005. logs.Error("FindByIdentify => ", err)
  1006. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  1007. return
  1008. }
  1009. bookId = bookResult.BookId
  1010. c.Data["Model"] = bookResult
  1011. editor = bookResult.Editor
  1012. }
  1013. if historyId <= 0 {
  1014. c.ShowErrorPage(60002, i18n.Tr(c.Lang, "message.param_error"))
  1015. }
  1016. history, err := models.NewDocumentHistory().Find(historyId)
  1017. if err != nil {
  1018. logs.Error("DocumentController.Compare => ", err)
  1019. c.ShowErrorPage(60003, err.Error())
  1020. }
  1021. doc, err := models.NewDocument().Find(history.DocumentId)
  1022. if err != nil || doc == nil || doc.BookId != bookId {
  1023. c.ShowErrorPage(60002, i18n.Tr(c.Lang, "message.doc_not_exist"))
  1024. return
  1025. }
  1026. c.Data["HistoryId"] = historyId
  1027. c.Data["DocumentId"] = doc.DocumentId
  1028. if editor == EditorMarkdown || editor == EditorCherryMarkdown {
  1029. c.Data["HistoryContent"] = history.Markdown
  1030. c.Data["Content"] = doc.Markdown
  1031. } else {
  1032. c.Data["HistoryContent"] = template.HTML(history.Content)
  1033. c.Data["Content"] = template.HTML(doc.Content)
  1034. }
  1035. }
  1036. // 判断用户是否可以阅读文档
  1037. func (c *DocumentController) isReadable(identify, token string) *models.BookResult {
  1038. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  1039. if err != nil {
  1040. logs.Error(err)
  1041. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.item_not_exist"))
  1042. }
  1043. bookResult := models.NewBookResult().ToBookResult(*book)
  1044. isOk := false
  1045. if c.isUserLoggedIn() {
  1046. roleId, err := models.NewBook().FindForRoleId(book.BookId, c.Member.MemberId)
  1047. if err == nil {
  1048. isOk = true
  1049. bookResult.MemberId = c.Member.MemberId
  1050. bookResult.RoleId = roleId
  1051. }
  1052. }
  1053. /* 私有项目:
  1054. * 管理员可以直接访问
  1055. * 参与者可以直接访问
  1056. * 其他用户(支持匿名访问)
  1057. * token设置情况
  1058. * 已设置:可以通过token访问
  1059. * 未设置:不可以通过token访问
  1060. * password设置情况
  1061. * 已设置:可以通过password访问
  1062. * 未设置:不可以通过password访问
  1063. * 注意:
  1064. * 1. 第一次访问需要存session
  1065. * 2. 有session优先使用session中的token或者password,再使用携带的token或者password
  1066. * 3. 私有项目如果token和password都没有设置,则除管理员和参与者的其他用户不可以访问
  1067. * 4. 使用token访问如果不通过,则提示输入密码
  1068. */
  1069. if book.PrivatelyOwned == 1 {
  1070. if c.isUserLoggedIn() && c.Member.IsAdministrator() {
  1071. return bookResult
  1072. }
  1073. if isOk { // Project participant.
  1074. return bookResult
  1075. }
  1076. // Use session in preference.
  1077. if tokenOrPassword, ok := c.GetSession(identify).(string); ok {
  1078. if strings.EqualFold(book.PrivateToken, tokenOrPassword) || strings.EqualFold(book.BookPassword, tokenOrPassword) {
  1079. return bookResult
  1080. }
  1081. }
  1082. // Next: Session not exist or not correct.
  1083. if book.PrivateToken != "" && book.PrivateToken == token {
  1084. c.SetSession(identify, token)
  1085. return bookResult
  1086. } else if book.BookPassword != "" {
  1087. // Send a page for inputting password.
  1088. // For verification, see function DocumentController.CheckPassword
  1089. body, err := c.ExecuteViewPathTemplate("document/document_password.tpl",
  1090. map[string]string{"Identify": book.Identify, "Lang": c.Lang})
  1091. if err != nil {
  1092. logs.Error("显示密码页面失败 ->", err)
  1093. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  1094. }
  1095. c.CustomAbort(200, body)
  1096. } else {
  1097. // No permission to access this book.
  1098. logs.Info("尝试访问文档但权限不足 ->", identify, token)
  1099. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  1100. }
  1101. }
  1102. return bookResult
  1103. }
  1104. func promptUserToLogIn(c *DocumentController) {
  1105. logs.Info("Access " + c.Ctx.Request.URL.RequestURI() + " not permitted.")
  1106. logs.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID(context.TODO()) + ").")
  1107. if c.IsAjax() {
  1108. c.JsonResult(6000, i18n.Tr(c.Lang, "message.need_relogin"))
  1109. } else {
  1110. c.Redirect(conf.URLFor("AccountController.Login")+"?url="+url.PathEscape(conf.BaseUrl+c.Ctx.Request.URL.RequestURI()), 302)
  1111. }
  1112. }