document.go 33 KB

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