DocumentController.go 33 KB

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