DocumentController.go 40 KB

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