DocumentController.go 33 KB

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