document.go 31 KB

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