page.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. module.exports = function(crowi) {
  2. var debug = require('debug')('crowi:models:page')
  3. , mongoose = require('mongoose')
  4. , escapeStringRegexp = require('escape-string-regexp')
  5. , ObjectId = mongoose.Schema.Types.ObjectId
  6. , GRANT_PUBLIC = 1
  7. , GRANT_RESTRICTED = 2
  8. , GRANT_SPECIFIED = 3
  9. , GRANT_OWNER = 4
  10. , PAGE_GRANT_ERROR = 1
  11. , STATUS_WIP = 'wip'
  12. , STATUS_PUBLISHED = 'published'
  13. , STATUS_DELETED = 'deleted'
  14. , STATUS_DEPRECATED = 'deprecated'
  15. , pageEvent = crowi.event('page')
  16. , pageSchema;
  17. function isPortalPath(path) {
  18. if (path.match(/.*\/$/)) {
  19. return true;
  20. }
  21. return false;
  22. }
  23. pageSchema = new mongoose.Schema({
  24. path: { type: String, required: true, index: true, unique: true },
  25. revision: { type: ObjectId, ref: 'Revision' },
  26. redirectTo: { type: String, index: true },
  27. status: { type: String, default: STATUS_PUBLISHED, index: true },
  28. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  29. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  30. creator: { type: ObjectId, ref: 'User', index: true },
  31. // lastUpdateUser: this schema is from 1.5.x (by deletion feature), and null is default.
  32. // the last update user on the screen is by revesion.author for B.C.
  33. lastUpdateUser: { type: ObjectId, ref: 'User', index: true },
  34. liker: [{ type: ObjectId, ref: 'User', index: true }],
  35. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  36. commentCount: { type: Number, default: 0 },
  37. extended: {
  38. type: String,
  39. default: '{}',
  40. get: function(data) {
  41. try {
  42. return JSON.parse(data);
  43. } catch(e) {
  44. return data;
  45. }
  46. },
  47. set: function(data) {
  48. return JSON.stringify(data);
  49. }
  50. },
  51. createdAt: { type: Date, default: Date.now },
  52. updatedAt: Date
  53. }, {
  54. toJSON: {getters: true},
  55. toObject: {getters: true}
  56. });
  57. pageEvent.on('create', pageEvent.onCreate);
  58. pageEvent.on('update', pageEvent.onUpdate);
  59. pageSchema.methods.isWIP = function() {
  60. return this.status === STATUS_WIP;
  61. };
  62. pageSchema.methods.isPublished = function() {
  63. // null: this is for B.C.
  64. return this.status === null || this.status === STATUS_PUBLISHED;
  65. };
  66. pageSchema.methods.isDeleted = function() {
  67. return this.status === STATUS_DELETED;
  68. };
  69. pageSchema.methods.isDeprecated = function() {
  70. return this.status === STATUS_DEPRECATED;
  71. };
  72. pageSchema.methods.isPublic = function() {
  73. if (!this.grant || this.grant == GRANT_PUBLIC) {
  74. return true;
  75. }
  76. return false;
  77. };
  78. pageSchema.methods.isPortal = function() {
  79. return isPortalPath(this.path);
  80. };
  81. pageSchema.methods.isCreator = function(userData) {
  82. if (this.populated('creator') && this.creator._id.toString() === userData._id.toString()) {
  83. return true;
  84. } else if (this.creator.toString() === userData._id.toString()) {
  85. return true
  86. }
  87. return false;
  88. };
  89. pageSchema.methods.isGrantedFor = function(userData) {
  90. if (this.isPublic() || this.isCreator(userData)) {
  91. return true;
  92. }
  93. if (this.grantedUsers.indexOf(userData._id) >= 0) {
  94. return true;
  95. }
  96. return false;
  97. };
  98. pageSchema.methods.isLatestRevision = function() {
  99. // populate されていなくて判断できない
  100. if (!this.latestRevision || !this.revision) {
  101. return true;
  102. }
  103. return (this.latestRevision == this.revision._id.toString());
  104. };
  105. pageSchema.methods.isUpdatable = function(previousRevision) {
  106. var revision = this.latestRevision || this.revision;
  107. if (revision != previousRevision) {
  108. return false;
  109. }
  110. return true;
  111. };
  112. pageSchema.methods.isLiked = function(userData) {
  113. return this.liker.some(function(likedUser) {
  114. return likedUser == userData._id.toString();
  115. });
  116. };
  117. pageSchema.methods.like = function(userData) {
  118. var self = this,
  119. Page = self;
  120. return new Promise(function(resolve, reject) {
  121. var added = self.liker.addToSet(userData._id);
  122. if (added.length > 0) {
  123. self.save(function(err, data) {
  124. if (err) {
  125. return reject(err);
  126. }
  127. debug('liker updated!', added);
  128. return resolve(data);
  129. });
  130. } else {
  131. debug('liker not updated');
  132. return reject(self);
  133. }
  134. });
  135. };
  136. pageSchema.methods.unlike = function(userData, callback) {
  137. var self = this,
  138. Page = self;
  139. return new Promise(function(resolve, reject) {
  140. var beforeCount = self.liker.length;
  141. self.liker.pull(userData._id);
  142. if (self.liker.length != beforeCount) {
  143. self.save(function(err, data) {
  144. if (err) {
  145. return reject(err);
  146. }
  147. return resolve(data);
  148. });
  149. } else {
  150. debug('liker not updated');
  151. return reject(self);
  152. }
  153. });
  154. };
  155. pageSchema.methods.isSeenUser = function(userData) {
  156. var self = this,
  157. Page = self;
  158. return this.seenUsers.some(function(seenUser) {
  159. return seenUser.equals(userData._id);
  160. });
  161. };
  162. pageSchema.methods.seen = function(userData) {
  163. var self = this,
  164. Page = self;
  165. if (this.isSeenUser(userData)) {
  166. debug('seenUsers not updated');
  167. return Promise.resolve(this);
  168. }
  169. return new Promise(function(resolve, reject) {
  170. if (!userData || !userData._id) {
  171. reject(new Error('User data is not valid'));
  172. }
  173. var added = self.seenUsers.addToSet(userData);
  174. self.save(function(err, data) {
  175. if (err) {
  176. return reject(err);
  177. }
  178. debug('seenUsers updated!', added);
  179. return resolve(self);
  180. });
  181. });
  182. };
  183. pageSchema.methods.getSlackChannel = function() {
  184. var extended = this.get('extended');
  185. if (!extended) {
  186. return '';
  187. }
  188. return extended.slack || '';
  189. };
  190. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  191. var extended = this.extended;
  192. extended.slack = slackChannel;
  193. return this.updateExtended(extended);
  194. };
  195. pageSchema.methods.updateExtended = function(extended) {
  196. var page = this;
  197. page.extended = extended;
  198. return new Promise(function(resolve, reject) {
  199. return page.save(function(err, doc) {
  200. if (err) {
  201. return reject(err);
  202. }
  203. return resolve(doc);
  204. });
  205. });
  206. };
  207. pageSchema.statics.populatePageData = function(pageData, revisionId) {
  208. var Page = crowi.model('Page');
  209. var User = crowi.model('User');
  210. pageData.latestRevision = pageData.revision;
  211. if (revisionId) {
  212. pageData.revision = revisionId;
  213. }
  214. pageData.likerCount = pageData.liker.length || 0;
  215. pageData.seenUsersCount = pageData.seenUsers.length || 0;
  216. return new Promise(function(resolve, reject) {
  217. pageData.populate([
  218. {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS},
  219. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  220. {path: 'revision', model: 'Revision'},
  221. //{path: 'liker', options: { limit: 11 }},
  222. //{path: 'seenUsers', options: { limit: 11 }},
  223. ], function (err, pageData) {
  224. Page.populate(pageData, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  225. if (err) {
  226. return reject(err);
  227. }
  228. return resolve(data);
  229. });
  230. });
  231. });
  232. };
  233. pageSchema.statics.populatePageListToAnyObjects = function(pageIdObjectArray) {
  234. var Page = this;
  235. var pageIdMappings = {};
  236. var pageIds = pageIdObjectArray.map(function(page, idx) {
  237. if (!page._id) {
  238. throw new Error('Pass the arg of populatePageListToAnyObjects() must have _id on each element.');
  239. }
  240. pageIdMappings[String(page._id)] = idx;
  241. return page._id;
  242. });
  243. return new Promise(function(resolve, reject) {
  244. Page.findListByPageIds(pageIds, {limit: 100}) // limit => if the pagIds is greater than 100, ignore
  245. .then(function(pages) {
  246. pages.forEach(function(page) {
  247. Object.assign(pageIdObjectArray[pageIdMappings[String(page._id)]], page._doc);
  248. });
  249. resolve(pageIdObjectArray);
  250. });
  251. });
  252. };
  253. pageSchema.statics.updateCommentCount = function (page, num)
  254. {
  255. var self = this;
  256. return new Promise(function(resolve, reject) {
  257. self.update({_id: page}, {commentCount: num}, {}, function(err, data) {
  258. if (err) {
  259. debug('Update commentCount Error', err);
  260. return reject(err);
  261. }
  262. return resolve(data);
  263. });
  264. });
  265. };
  266. pageSchema.statics.hasPortalPage = function (path, user, revisionId) {
  267. var self = this;
  268. return new Promise(function(resolve, reject) {
  269. self.findPage(path, user, revisionId)
  270. .then(function(page) {
  271. resolve(page);
  272. }).catch(function(err) {
  273. resolve(null); // check only has portal page, through error
  274. });
  275. });
  276. };
  277. pageSchema.statics.getGrantLabels = function() {
  278. var grantLabels = {};
  279. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  280. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  281. //grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  282. grantLabels[GRANT_OWNER] = 'Just me'; // 自分のみ
  283. return grantLabels;
  284. };
  285. pageSchema.statics.normalizePath = function(path) {
  286. if (!path.match(/^\//)) {
  287. path = '/' + path;
  288. }
  289. path = path.replace(/\/\s+?/g, '/').replace(/\s+\//g, '/');
  290. return path;
  291. };
  292. pageSchema.statics.getUserPagePath = function(user) {
  293. return '/user/' + user.username;
  294. };
  295. pageSchema.statics.getDeletedPageName = function(path) {
  296. if (path.match('\/')) {
  297. path = path.substr(1);
  298. }
  299. return '/trash/' + path;
  300. };
  301. pageSchema.statics.getRevertDeletedPageName = function(path) {
  302. return path.replace('\/trash', '');
  303. };
  304. pageSchema.statics.isDeletableName = function(path) {
  305. var notDeletable = [
  306. /^\/user\/[^\/]+$/, // user page
  307. ];
  308. for (var i = 0; i < notDeletable.length; i++) {
  309. var pattern = notDeletable[i];
  310. if (path.match(pattern)) {
  311. return false;
  312. }
  313. }
  314. return true;
  315. };
  316. pageSchema.statics.isCreatableName = function(name) {
  317. var forbiddenPages = [
  318. /\^|\$|\*|\+|\#/,
  319. /^\/_.*/, // /_api/* and so on
  320. /^\/\-\/.*/,
  321. /^\/_r\/.*/,
  322. /^\/user\/[^\/]+\/(bookmarks|comments|activities|pages|recent-create|recent-edit)/, // reserved
  323. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  324. /\/{2,}/, // avoid miss in renaming
  325. /\s+\/\s+/, // avoid miss in renaming
  326. /.+\/edit$/,
  327. /.+\.md$/,
  328. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  329. ];
  330. var isCreatable = true;
  331. forbiddenPages.forEach(function(page) {
  332. var pageNameReg = new RegExp(page);
  333. if (name.match(pageNameReg)) {
  334. isCreatable = false;
  335. return ;
  336. }
  337. });
  338. return isCreatable;
  339. };
  340. pageSchema.statics.fixToCreatableName = function(path) {
  341. return path
  342. .replace(/\/\//g, '/')
  343. ;
  344. };
  345. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  346. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  347. cb(err, data);
  348. });
  349. };
  350. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  351. this
  352. .find({})
  353. .sort({updatedAt: -1})
  354. .skip(offset)
  355. .limit(limit)
  356. .exec(function(err, data) {
  357. cb(err, data);
  358. });
  359. };
  360. pageSchema.statics.findPageById = function(id) {
  361. var Page = this;
  362. return new Promise(function(resolve, reject) {
  363. Page.findOne({_id: id}, function(err, pageData) {
  364. if (err) {
  365. return reject(err);
  366. }
  367. if (pageData == null) {
  368. return reject(new Error('Page not found'));
  369. }
  370. return Page.populatePageData(pageData, null).then(resolve);
  371. });
  372. });
  373. };
  374. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  375. var Page = this;
  376. return new Promise(function(resolve, reject) {
  377. Page.findPageById(id)
  378. .then(function(pageData) {
  379. if (userData && !pageData.isGrantedFor(userData)) {
  380. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  381. }
  382. return resolve(pageData);
  383. }).catch(function(err) {
  384. return reject(err);
  385. });
  386. });
  387. };
  388. // find page and check if granted user
  389. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  390. var self = this;
  391. return new Promise(function(resolve, reject) {
  392. self.findOne({path: path}, function(err, pageData) {
  393. if (err) {
  394. return reject(err);
  395. }
  396. if (pageData === null) {
  397. if (ignoreNotFound) {
  398. return resolve(null);
  399. }
  400. var pageNotFoundError = new Error('Page Not Found')
  401. pageNotFoundError.name = 'Crowi:Page:NotFound';
  402. return reject(pageNotFoundError);
  403. }
  404. if (!pageData.isGrantedFor(userData)) {
  405. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  406. }
  407. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  408. });
  409. });
  410. };
  411. // find page by path
  412. pageSchema.statics.findPageByPath = function(path) {
  413. var Page = this;
  414. return new Promise(function(resolve, reject) {
  415. Page.findOne({path: path}, function(err, pageData) {
  416. if (err || pageData === null) {
  417. return reject(err);
  418. }
  419. return resolve(pageData);
  420. });
  421. });
  422. };
  423. pageSchema.statics.findListByPageIds = function(ids, options) {
  424. var Page = this;
  425. var User = crowi.model('User');
  426. var options = options || {}
  427. , limit = options.limit || 50
  428. , offset = options.skip || 0
  429. ;
  430. return new Promise(function(resolve, reject) {
  431. Page
  432. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  433. //.sort({createdAt: -1}) // TODO optionize
  434. .skip(offset)
  435. .limit(limit)
  436. .populate([
  437. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  438. {path: 'revision', model: 'Revision'},
  439. ])
  440. .exec(function(err, pages) {
  441. if (err) {
  442. return reject(err);
  443. }
  444. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  445. if (err) {
  446. return reject(err);
  447. }
  448. return resolve(data);
  449. });
  450. });
  451. });
  452. };
  453. pageSchema.statics.findPageByRedirectTo = function(path) {
  454. var Page = this;
  455. return new Promise(function(resolve, reject) {
  456. Page.findOne({redirectTo: path}, function(err, pageData) {
  457. if (err || pageData === null) {
  458. return reject(err);
  459. }
  460. return resolve(pageData);
  461. });
  462. });
  463. };
  464. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  465. var Page = this;
  466. var User = crowi.model('User');
  467. var limit = option.limit || 50;
  468. var offset = option.offset || 0;
  469. var conditions = {
  470. creator: user._id,
  471. redirectTo: null,
  472. $or: [
  473. {status: null},
  474. {status: STATUS_PUBLISHED},
  475. ],
  476. };
  477. if (!user.equals(currentUser._id)) {
  478. conditions.grant = GRANT_PUBLIC;
  479. }
  480. return new Promise(function(resolve, reject) {
  481. Page
  482. .find(conditions)
  483. .sort({createdAt: -1})
  484. .skip(offset)
  485. .limit(limit)
  486. .populate('revision')
  487. .exec()
  488. .then(function(pages) {
  489. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  490. });
  491. });
  492. };
  493. /**
  494. * Bulk get (for internal only)
  495. */
  496. pageSchema.statics.getStreamOfFindAll = function(options) {
  497. var Page = this
  498. , options = options || {}
  499. , publicOnly = options.publicOnly || true
  500. , criteria = {redirectTo: null,}
  501. ;
  502. if (publicOnly) {
  503. criteria.grant = GRANT_PUBLIC;
  504. }
  505. return this.find(criteria)
  506. .populate([
  507. {path: 'creator', model: 'User'},
  508. {path: 'revision', model: 'Revision'},
  509. ])
  510. .sort({updatedAt: -1})
  511. .cursor();
  512. };
  513. /**
  514. * find the page that is match with `path` and its descendants
  515. *
  516. * 1. `/` will be added to the end of `path`
  517. * 2. the regex strings included in `path` will be escaped
  518. */
  519. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  520. var Page = this;
  521. // add slash to the last
  522. path = Page.addSlashOfEnd(path);
  523. // escape
  524. path = escapeStringRegexp(path);
  525. return Page.findListByStartWith(path, userData, option);
  526. };
  527. /**
  528. * find pages that start with `path`
  529. *
  530. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  531. * If `path` doesn't have `/` at the end, returns '{path}*'
  532. */
  533. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  534. var Page = this;
  535. var User = crowi.model('User');
  536. if (!option) {
  537. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  538. }
  539. var opt = {
  540. sort: option.sort || 'updatedAt',
  541. desc: option.desc || -1,
  542. offset: option.offset || 0,
  543. limit: option.limit || 50
  544. };
  545. var sortOpt = {};
  546. sortOpt[opt.sort] = opt.desc;
  547. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  548. return new Promise(function(resolve, reject) {
  549. var q = Page.generateQueryToListByStartWith(path, userData, option)
  550. .sort(sortOpt)
  551. .skip(opt.offset)
  552. .limit(opt.limit);
  553. // retrieve revision data
  554. if (isPopulateRevisionBody) {
  555. q = q.populate('revision');
  556. }
  557. else {
  558. q = q.populate('revision', '-body'); // exclude body
  559. }
  560. q.exec()
  561. .then(function(pages) {
  562. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  563. .then(resolve)
  564. .catch(reject);
  565. })
  566. });
  567. };
  568. /**
  569. * generate the query to find the page that is match with `path` and its descendants
  570. *
  571. * 1. `/` will be added to the end of `path`
  572. * 2. the regex strings included in `path` will be escaped
  573. */
  574. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  575. var Page = this;
  576. // add slash to the last
  577. path = Page.addSlashOfEnd(path);
  578. // escape
  579. path = escapeStringRegexp(path);
  580. return Page.generateQueryToListByStartWith(path, userData, option);
  581. };
  582. /**
  583. * generate the query to find pages that start with `path`
  584. *
  585. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  586. * If `path` doesn't have `/` at the end, returns '{path}*'
  587. */
  588. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  589. var Page = this;
  590. var pathCondition = [];
  591. var includeDeletedPage = option.includeDeletedPage || false;
  592. var queryReg = new RegExp('^' + path);
  593. pathCondition.push({path: queryReg});
  594. if (path.match(/\/$/)) {
  595. debug('Page list by ending with /, so find also upper level page');
  596. pathCondition.push({path: path.substr(0, path.length -1)});
  597. }
  598. var q = Page.find({
  599. redirectTo: null,
  600. $or: [
  601. {grant: null},
  602. {grant: GRANT_PUBLIC},
  603. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  604. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  605. {grant: GRANT_OWNER, grantedUsers: userData._id},
  606. ],})
  607. .and({
  608. $or: pathCondition
  609. });
  610. if (!includeDeletedPage) {
  611. q.and({
  612. $or: [
  613. {status: null},
  614. {status: STATUS_PUBLISHED},
  615. ],
  616. });
  617. }
  618. return q;
  619. }
  620. pageSchema.statics.updatePageProperty = function(page, updateData) {
  621. var Page = this;
  622. return new Promise(function(resolve, reject) {
  623. // TODO foreach して save
  624. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  625. if (err) {
  626. return reject(err);
  627. }
  628. return resolve(data);
  629. });
  630. });
  631. };
  632. pageSchema.statics.updateGrant = function(page, grant, userData) {
  633. var Page = this;
  634. return new Promise(function(resolve, reject) {
  635. page.grant = grant;
  636. if (grant == GRANT_PUBLIC) {
  637. page.grantedUsers = [];
  638. } else {
  639. page.grantedUsers = [];
  640. page.grantedUsers.push(userData._id);
  641. }
  642. page.save(function(err, data) {
  643. debug('Page.updateGrant, saved grantedUsers.', err, data);
  644. if (err) {
  645. return reject(err);
  646. }
  647. return resolve(data);
  648. });
  649. });
  650. };
  651. // Instance method でいいのでは
  652. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  653. return new Promise(function(resolve, reject) {
  654. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  655. page.grantedUsers = [];
  656. }
  657. page.grantedUsers.push(userData);
  658. page.save(function(err, data) {
  659. if (err) {
  660. return reject(err);
  661. }
  662. return resolve(data);
  663. });
  664. });
  665. };
  666. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  667. var isCreate = false;
  668. if (pageData.revision === undefined) {
  669. debug('pushRevision on Create');
  670. isCreate = true;
  671. }
  672. return new Promise(function(resolve, reject) {
  673. newRevision.save(function(err, newRevision) {
  674. if (err) {
  675. debug('Error on saving revision', err);
  676. return reject(err);
  677. }
  678. debug('Successfully saved new revision', newRevision);
  679. pageData.revision = newRevision;
  680. pageData.lastUpdateUser = user;
  681. pageData.updatedAt = Date.now();
  682. pageData.save(function(err, data) {
  683. if (err) {
  684. // todo: remove new revision?
  685. debug('Error on save page data (after push revision)', err);
  686. return reject(err);
  687. }
  688. resolve(data);
  689. if (!isCreate) {
  690. debug('pushRevision on Update');
  691. }
  692. });
  693. });
  694. });
  695. };
  696. pageSchema.statics.create = function(path, body, user, options) {
  697. var Page = this
  698. , Revision = crowi.model('Revision')
  699. , format = options.format || 'markdown'
  700. , grant = options.grant || GRANT_PUBLIC
  701. , redirectTo = options.redirectTo || null;
  702. // force public
  703. if (isPortalPath(path)) {
  704. grant = GRANT_PUBLIC;
  705. }
  706. return new Promise(function(resolve, reject) {
  707. Page.findOne({path: path}, function(err, pageData) {
  708. if (pageData) {
  709. return reject(new Error('Cannot create new page to existed path'));
  710. }
  711. var newPage = new Page();
  712. newPage.path = path;
  713. newPage.creator = user;
  714. newPage.lastUpdateUser = user;
  715. newPage.createdAt = Date.now();
  716. newPage.updatedAt = Date.now();
  717. newPage.redirectTo = redirectTo;
  718. newPage.grant = grant;
  719. newPage.status = STATUS_PUBLISHED;
  720. newPage.grantedUsers = [];
  721. newPage.grantedUsers.push(user);
  722. newPage.save(function (err, newPage) {
  723. if (err) {
  724. return reject(err);
  725. }
  726. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  727. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  728. resolve(data);
  729. pageEvent.emit('create', data, user);
  730. }).catch(function(err) {
  731. debug('Push Revision Error on create page', err);
  732. return reject(err);
  733. });
  734. });
  735. });
  736. });
  737. };
  738. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  739. var Page = this
  740. , Revision = crowi.model('Revision')
  741. , grant = options.grant || null
  742. ;
  743. // update existing page
  744. var newRevision = Revision.prepareRevision(pageData, body, user);
  745. return new Promise(function(resolve, reject) {
  746. Page.pushRevision(pageData, newRevision, user)
  747. .then(function(revision) {
  748. if (grant != pageData.grant) {
  749. return Page.updateGrant(pageData, grant, user).then(function(data) {
  750. debug('Page grant update:', data);
  751. resolve(data);
  752. pageEvent.emit('update', data, user);
  753. });
  754. } else {
  755. resolve(pageData);
  756. pageEvent.emit('update', pageData, user);
  757. }
  758. }).catch(function(err) {
  759. debug('Error on update', err);
  760. debug('Error on update', err.stack);
  761. });
  762. });
  763. };
  764. pageSchema.statics.deletePage = function(pageData, user, options) {
  765. var Page = this
  766. , newPath = Page.getDeletedPageName(pageData.path)
  767. ;
  768. if (Page.isDeletableName(pageData.path)) {
  769. return new Promise(function(resolve, reject) {
  770. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  771. .then(function(data) {
  772. pageData.status = STATUS_DELETED;
  773. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  774. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  775. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  776. debug('Deleted the page, and rename it', pageData.path, newPath);
  777. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  778. }).then(function(pageData) {
  779. resolve(pageData);
  780. }).catch(reject);
  781. });
  782. } else {
  783. return Promise.reject('Page is not deletable.');
  784. }
  785. };
  786. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  787. var Page = this
  788. , path = pageData.path
  789. , options = options || {}
  790. ;
  791. return new Promise(function (resolve, reject) {
  792. Page
  793. .generateQueryToListWithDescendants(path, user, options)
  794. .then(function (pages) {
  795. Promise.all(pages.map(function (page) {
  796. return Page.deletePage(page, user, options);
  797. }))
  798. .then(function (data) {
  799. return resolve(pageData);
  800. });
  801. });
  802. });
  803. };
  804. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  805. var Page = this
  806. , newPath = Page.getRevertDeletedPageName(pageData.path)
  807. ;
  808. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  809. // そのため、そいつは削除してOK
  810. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  811. return new Promise(function(resolve, reject) {
  812. Page.findPageByPath(newPath)
  813. .then(function(originPageData) {
  814. if (originPageData.redirectTo !== pageData.path) {
  815. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  816. }
  817. return Page.completelyDeletePage(originPageData);
  818. }).then(function(done) {
  819. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  820. }).then(function(done) {
  821. pageData.status = STATUS_PUBLISHED;
  822. debug('Revert deleted the page, and rename again it', pageData, newPath);
  823. return Page.rename(pageData, newPath, user, {})
  824. }).then(function(done) {
  825. pageData.path = newPath;
  826. resolve(pageData);
  827. }).catch(reject);
  828. });
  829. };
  830. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  831. var Page = this
  832. , path = pageData.path
  833. , options = options || { includeDeletedPage: true}
  834. ;
  835. return new Promise(function (resolve, reject) {
  836. Page
  837. .generateQueryToListWithDescendants(path, user, options)
  838. .then(function (pages) {
  839. Promise.all(pages.map(function (page) {
  840. return Page.revertDeletedPage(page, user, options);
  841. }))
  842. .then(function (data) {
  843. return resolve(data[0]);
  844. });
  845. });
  846. });
  847. };
  848. /**
  849. * This is danger.
  850. */
  851. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  852. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  853. var Bookmark = crowi.model('Bookmark')
  854. , Attachment = crowi.model('Attachment')
  855. , Comment = crowi.model('Comment')
  856. , Revision = crowi.model('Revision')
  857. , Page = this
  858. , pageId = pageData._id
  859. ;
  860. debug('Completely delete', pageData.path);
  861. return new Promise(function(resolve, reject) {
  862. Bookmark.removeBookmarksByPageId(pageId)
  863. .then(function(done) {
  864. }).then(function(done) {
  865. return Attachment.removeAttachmentsByPageId(pageId);
  866. }).then(function(done) {
  867. return Comment.removeCommentsByPageId(pageId);
  868. }).then(function(done) {
  869. return Revision.removeRevisionsByPath(pageData.path);
  870. }).then(function(done) {
  871. return Page.removePageById(pageId);
  872. }).then(function(done) {
  873. return Page.removeRedirectOriginPageByPath(pageData.path);
  874. }).then(function(done) {
  875. pageEvent.emit('delete', pageData, user); // update as renamed page
  876. resolve(pageData);
  877. }).catch(reject);
  878. });
  879. };
  880. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  881. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  882. var Page = this
  883. , path = pageData.path
  884. , options = options || { includeDeletedPage: true }
  885. ;
  886. return new Promise(function (resolve, reject) {
  887. Page
  888. .generateQueryToListWithDescendants(path, user, options)
  889. .then(function (pages) {
  890. Promise.all(pages.map(function (page) {
  891. return Page.completelyDeletePage(page, user, options);
  892. }))
  893. .then(function (data) {
  894. return resolve(data[0]);
  895. });
  896. });
  897. });
  898. };
  899. pageSchema.statics.removePageById = function(pageId) {
  900. var Page = this;
  901. return new Promise(function(resolve, reject) {
  902. Page.remove({_id: pageId}, function(err, done) {
  903. debug('Remove phisiaclly, the page', pageId, err, done);
  904. if (err) {
  905. return reject(err);
  906. }
  907. resolve(done);
  908. });
  909. });
  910. };
  911. pageSchema.statics.removePageByPath = function(pagePath) {
  912. var Page = this;
  913. return Page.findPageByPath(pagePath)
  914. .then(function(pageData) {
  915. return Page.removePageById(pageData.id);
  916. });
  917. };
  918. /**
  919. * remove the page that is redirecting to specified `pagePath` recursively
  920. * ex: when
  921. * '/page1' redirects to '/page2' and
  922. * '/page2' redirects to '/page3'
  923. * and given '/page3',
  924. * '/page1' and '/page2' will be removed
  925. *
  926. * @param {string} pagePath
  927. */
  928. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  929. var Page = this;
  930. return Page.findPageByRedirectTo(pagePath)
  931. .then((redirectOriginPageData) => {
  932. // remove
  933. return Page.removePageById(redirectOriginPageData.id)
  934. // remove recursive
  935. .then(() => {
  936. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  937. });
  938. })
  939. .catch((err) => {
  940. // do nothing if origin page doesn't exist
  941. return Promise.resolve();
  942. })
  943. };
  944. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  945. var Page = this
  946. , Revision = crowi.model('Revision')
  947. , path = pageData.path
  948. , createRedirectPage = options.createRedirectPage || 0
  949. , moveUnderTrees = options.moveUnderTrees || 0;
  950. return new Promise(function(resolve, reject) {
  951. // pageData の path を変更
  952. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  953. .then(function(data) {
  954. // reivisions の path を変更
  955. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  956. }).then(function(data) {
  957. pageData.path = newPagePath;
  958. if (createRedirectPage) {
  959. var body = 'redirect ' + newPagePath;
  960. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  961. } else {
  962. resolve(data);
  963. }
  964. pageEvent.emit('update', pageData, user); // update as renamed page
  965. });
  966. });
  967. };
  968. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  969. var Page = this
  970. , path = pageData.path
  971. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  972. return new Promise(function(resolve, reject) {
  973. Page
  974. .generateQueryToListWithDescendants(path, user, options)
  975. .then(function(pages) {
  976. Promise.all(pages.map(function(page) {
  977. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  978. return Page.rename(page, newPagePath, user, options);
  979. }))
  980. .then(function() {
  981. pageData.path = newPagePathPrefix;
  982. return resolve();
  983. });
  984. });
  985. });
  986. };
  987. pageSchema.statics.getHistories = function() {
  988. // TODO
  989. return;
  990. };
  991. /**
  992. * return path that added slash to the end for specified path
  993. */
  994. pageSchema.statics.addSlashOfEnd = function(path) {
  995. let returnPath = path;
  996. if (!path.match(/\/$/)) {
  997. returnPath += '/';
  998. }
  999. return returnPath;
  1000. }
  1001. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1002. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1003. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1004. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1005. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1006. return mongoose.model('Page', pageSchema);
  1007. };