document.go 32 KB

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