document.go 32 KB

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