DocumentController.go 34 KB

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