DocumentController.go 37 KB

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