1
0

DocumentController.go 41 KB

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