page.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. /* eslint-disable no-use-before-define */
  4. const logger = require('@alias/logger')('growi:models:page');
  5. const debug = require('debug')('growi:models:page');
  6. const nodePath = require('path');
  7. const urljoin = require('url-join');
  8. const mongoose = require('mongoose');
  9. const mongoosePaginate = require('mongoose-paginate-v2');
  10. const uniqueValidator = require('mongoose-unique-validator');
  11. const differenceInYears = require('date-fns/differenceInYears');
  12. const { pathUtils } = require('growi-commons');
  13. const templateChecker = require('@commons/util/template-checker');
  14. const { isTopPage } = require('@commons/util/path-utils');
  15. const escapeStringRegexp = require('escape-string-regexp');
  16. const ObjectId = mongoose.Schema.Types.ObjectId;
  17. /*
  18. * define schema
  19. */
  20. const GRANT_PUBLIC = 1;
  21. const GRANT_RESTRICTED = 2;
  22. const GRANT_SPECIFIED = 3;
  23. const GRANT_OWNER = 4;
  24. const GRANT_USER_GROUP = 5;
  25. const PAGE_GRANT_ERROR = 1;
  26. const STATUS_PUBLISHED = 'published';
  27. const STATUS_DELETED = 'deleted';
  28. const pageSchema = new mongoose.Schema({
  29. path: {
  30. type: String, required: true, index: true, unique: true,
  31. },
  32. revision: { type: ObjectId, ref: 'Revision' },
  33. redirectTo: { type: String, index: true },
  34. status: { type: String, default: STATUS_PUBLISHED, index: true },
  35. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  36. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  37. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  38. creator: { type: ObjectId, ref: 'User', index: true },
  39. lastUpdateUser: { type: ObjectId, ref: 'User' },
  40. liker: [{ type: ObjectId, ref: 'User' }],
  41. seenUsers: [{ type: ObjectId, ref: 'User' }],
  42. commentCount: { type: Number, default: 0 },
  43. extended: {
  44. type: String,
  45. default: '{}',
  46. get(data) {
  47. try {
  48. return JSON.parse(data);
  49. }
  50. catch (e) {
  51. return data;
  52. }
  53. },
  54. set(data) {
  55. return JSON.stringify(data);
  56. },
  57. },
  58. pageIdOnHackmd: String,
  59. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  60. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  61. createdAt: { type: Date, default: Date.now },
  62. updatedAt: { type: Date, default: Date.now },
  63. }, {
  64. toJSON: { getters: true },
  65. toObject: { getters: true },
  66. });
  67. // apply plugins
  68. pageSchema.plugin(mongoosePaginate);
  69. pageSchema.plugin(uniqueValidator);
  70. /**
  71. * return an array of ancestors paths that is extracted from specified pagePath
  72. * e.g.
  73. * when `pagePath` is `/foo/bar/baz`,
  74. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  75. *
  76. * @param {string} pagePath
  77. * @return {string[]} ancestors paths
  78. */
  79. const extractToAncestorsPaths = (pagePath) => {
  80. const ancestorsPaths = [];
  81. let parentPath;
  82. while (parentPath !== '/') {
  83. parentPath = nodePath.dirname(parentPath || pagePath);
  84. ancestorsPaths.push(parentPath);
  85. }
  86. return ancestorsPaths;
  87. };
  88. /**
  89. * populate page (Query or Document) to show revision
  90. * @param {any} page Query or Document
  91. * @param {string} userPublicFields string to set to select
  92. */
  93. /* eslint-disable object-curly-newline, object-property-newline */
  94. const populateDataToShowRevision = (page, userPublicFields) => {
  95. return page
  96. .populate([
  97. { path: 'lastUpdateUser', model: 'User', select: userPublicFields },
  98. { path: 'creator', model: 'User', select: userPublicFields },
  99. { path: 'grantedGroup', model: 'UserGroup' },
  100. { path: 'revision', model: 'Revision', populate: {
  101. path: 'author', model: 'User', select: userPublicFields,
  102. } },
  103. ]);
  104. };
  105. /* eslint-enable object-curly-newline, object-property-newline */
  106. class PageQueryBuilder {
  107. constructor(query) {
  108. this.query = query;
  109. }
  110. addConditionToExcludeTrashed() {
  111. this.query = this.query
  112. .and({
  113. $or: [
  114. { status: null },
  115. { status: STATUS_PUBLISHED },
  116. ],
  117. });
  118. return this;
  119. }
  120. addConditionToExcludeRedirect() {
  121. this.query = this.query.and({ redirectTo: null });
  122. return this;
  123. }
  124. /**
  125. * generate the query to find the pages '{path}/*' and '{path}' self.
  126. * If top page, return without doing anything.
  127. */
  128. addConditionToListWithDescendants(path, option) {
  129. // No request is set for the top page
  130. if (isTopPage(path)) {
  131. return this;
  132. }
  133. const pathNormalized = pathUtils.normalizePath(path);
  134. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  135. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  136. this.query = this.query
  137. .and({
  138. $or: [
  139. { path: pathNormalized },
  140. { path: new RegExp(`^${startsPattern}`) },
  141. ],
  142. });
  143. return this;
  144. }
  145. /**
  146. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  147. * If top page, return without doing anything.
  148. */
  149. addConditionToListOnlyDescendants(path, option) {
  150. // No request is set for the top page
  151. if (isTopPage(path)) {
  152. return this;
  153. }
  154. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  155. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  156. this.query = this.query
  157. .and({ path: new RegExp(`^${startsPattern}`) });
  158. return this;
  159. }
  160. /**
  161. * generate the query to find pages that start with `path`
  162. *
  163. * In normal case, returns '{path}/*' and '{path}' self.
  164. * If top page, return without doing anything.
  165. *
  166. * *option*
  167. * Left for backward compatibility
  168. */
  169. addConditionToListByStartWith(path, option) {
  170. // No request is set for the top page
  171. if (isTopPage(path)) {
  172. return this;
  173. }
  174. const startsPattern = escapeStringRegexp(path);
  175. this.query = this.query
  176. .and({ path: new RegExp(`^${startsPattern}`) });
  177. return this;
  178. }
  179. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  180. const grantConditions = [
  181. { grant: null },
  182. { grant: GRANT_PUBLIC },
  183. ];
  184. if (showAnyoneKnowsLink) {
  185. grantConditions.push({ grant: GRANT_RESTRICTED });
  186. }
  187. if (showPagesRestrictedByOwner) {
  188. grantConditions.push(
  189. { grant: GRANT_SPECIFIED },
  190. { grant: GRANT_OWNER },
  191. );
  192. }
  193. else if (user != null) {
  194. grantConditions.push(
  195. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  196. { grant: GRANT_OWNER, grantedUsers: user._id },
  197. );
  198. }
  199. if (showPagesRestrictedByGroup) {
  200. grantConditions.push(
  201. { grant: GRANT_USER_GROUP },
  202. );
  203. }
  204. else if (userGroups != null && userGroups.length > 0) {
  205. grantConditions.push(
  206. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  207. );
  208. }
  209. this.query = this.query
  210. .and({
  211. $or: grantConditions,
  212. });
  213. return this;
  214. }
  215. addConditionToPagenate(offset, limit, sortOpt) {
  216. this.query = this.query
  217. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  218. return this;
  219. }
  220. populateDataToList(userPublicFields) {
  221. this.query = this.query
  222. .populate({
  223. path: 'lastUpdateUser',
  224. select: userPublicFields,
  225. });
  226. return this;
  227. }
  228. populateDataToShowRevision(userPublicFields) {
  229. this.query = populateDataToShowRevision(this.query, userPublicFields);
  230. return this;
  231. }
  232. }
  233. module.exports = function(crowi) {
  234. let pageEvent;
  235. // init event
  236. if (crowi != null) {
  237. pageEvent = crowi.event('page');
  238. pageEvent.on('create', pageEvent.onCreate);
  239. pageEvent.on('update', pageEvent.onUpdate);
  240. }
  241. function validateCrowi() {
  242. if (crowi == null) {
  243. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  244. }
  245. }
  246. pageSchema.methods.isDeleted = function() {
  247. return (this.status === STATUS_DELETED) || checkIfTrashed(this.path);
  248. };
  249. pageSchema.methods.isPublic = function() {
  250. if (!this.grant || this.grant === GRANT_PUBLIC) {
  251. return true;
  252. }
  253. return false;
  254. };
  255. pageSchema.methods.isTopPage = function() {
  256. return isTopPage(this.path);
  257. };
  258. pageSchema.methods.isTemplate = function() {
  259. return templateChecker(this.path);
  260. };
  261. pageSchema.methods.isLatestRevision = function() {
  262. // populate されていなくて判断できない
  263. if (!this.latestRevision || !this.revision) {
  264. return true;
  265. }
  266. // comparing ObjectId with string
  267. // eslint-disable-next-line eqeqeq
  268. return (this.latestRevision == this.revision._id.toString());
  269. };
  270. pageSchema.methods.findRelatedTagsById = async function() {
  271. const PageTagRelation = mongoose.model('PageTagRelation');
  272. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  273. return relations.map((relation) => { return relation.relatedTag.name });
  274. };
  275. pageSchema.methods.isUpdatable = function(previousRevision) {
  276. const revision = this.latestRevision || this.revision;
  277. // comparing ObjectId with string
  278. // eslint-disable-next-line eqeqeq
  279. if (revision != previousRevision) {
  280. return false;
  281. }
  282. return true;
  283. };
  284. pageSchema.methods.isLiked = function(user) {
  285. if (user == null || user._id == null) {
  286. return false;
  287. }
  288. return this.liker.some((likedUserId) => {
  289. return likedUserId.toString() === user._id.toString();
  290. });
  291. };
  292. pageSchema.methods.like = function(userData) {
  293. const self = this;
  294. return new Promise(((resolve, reject) => {
  295. const added = self.liker.addToSet(userData._id);
  296. if (added.length > 0) {
  297. self.save((err, data) => {
  298. if (err) {
  299. return reject(err);
  300. }
  301. logger.debug('liker updated!', added);
  302. return resolve(data);
  303. });
  304. }
  305. else {
  306. logger.debug('liker not updated');
  307. return reject(self);
  308. }
  309. }));
  310. };
  311. pageSchema.methods.unlike = function(userData, callback) {
  312. const self = this;
  313. return new Promise(((resolve, reject) => {
  314. const beforeCount = self.liker.length;
  315. self.liker.pull(userData._id);
  316. if (self.liker.length !== beforeCount) {
  317. self.save((err, data) => {
  318. if (err) {
  319. return reject(err);
  320. }
  321. return resolve(data);
  322. });
  323. }
  324. else {
  325. logger.debug('liker not updated');
  326. return reject(self);
  327. }
  328. }));
  329. };
  330. pageSchema.methods.isSeenUser = function(userData) {
  331. return this.seenUsers.includes(userData._id);
  332. };
  333. pageSchema.methods.seen = async function(userData) {
  334. if (this.isSeenUser(userData)) {
  335. debug('seenUsers not updated');
  336. return this;
  337. }
  338. if (!userData || !userData._id) {
  339. throw new Error('User data is not valid');
  340. }
  341. const added = this.seenUsers.addToSet(userData);
  342. const saved = await this.save();
  343. debug('seenUsers updated!', added);
  344. return saved;
  345. };
  346. pageSchema.methods.getSlackChannel = function() {
  347. const extended = this.get('extended');
  348. if (!extended) {
  349. return '';
  350. }
  351. return extended.slack || '';
  352. };
  353. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  354. const extended = this.extended;
  355. extended.slack = slackChannel;
  356. return this.updateExtended(extended);
  357. };
  358. pageSchema.methods.updateExtended = function(extended) {
  359. const page = this;
  360. page.extended = extended;
  361. return new Promise(((resolve, reject) => {
  362. return page.save((err, doc) => {
  363. if (err) {
  364. return reject(err);
  365. }
  366. return resolve(doc);
  367. });
  368. }));
  369. };
  370. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  371. this.latestRevision = this.revision;
  372. if (revisionId != null) {
  373. this.revision = revisionId;
  374. }
  375. };
  376. pageSchema.methods.populateDataToShowRevision = async function() {
  377. validateCrowi();
  378. const User = crowi.model('User');
  379. return populateDataToShowRevision(this, User.USER_PUBLIC_FIELDS)
  380. .execPopulate();
  381. };
  382. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  383. this.latestRevision = this.revision;
  384. if (revisionId != null) {
  385. this.revision = revisionId;
  386. }
  387. return this.populate('revision').execPopulate();
  388. };
  389. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  390. // reset
  391. this.grantedUsers = [];
  392. this.grantedGroup = null;
  393. this.grant = grant || GRANT_PUBLIC;
  394. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  395. this.grantedUsers.push(user._id);
  396. }
  397. if (grant === GRANT_USER_GROUP) {
  398. this.grantedGroup = grantUserGroupId;
  399. }
  400. };
  401. pageSchema.methods.getContentAge = function() {
  402. return differenceInYears(new Date(), this.updatedAt);
  403. };
  404. pageSchema.statics.updateCommentCount = function(pageId) {
  405. validateCrowi();
  406. const self = this;
  407. const Comment = crowi.model('Comment');
  408. return Comment.countCommentByPageId(pageId)
  409. .then((count) => {
  410. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  411. if (err) {
  412. debug('Update commentCount Error', err);
  413. throw err;
  414. }
  415. return data;
  416. });
  417. });
  418. };
  419. pageSchema.statics.getGrantLabels = function() {
  420. const grantLabels = {};
  421. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  422. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  423. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  424. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  425. grantLabels[GRANT_OWNER] = 'Only me'; // 自分のみ
  426. return grantLabels;
  427. };
  428. pageSchema.statics.getUserPagePath = function(user) {
  429. return `/user/${user.username}`;
  430. };
  431. pageSchema.statics.getDeletedPageName = function(path) {
  432. if (path.match('/')) {
  433. // eslint-disable-next-line no-param-reassign
  434. path = path.substr(1);
  435. }
  436. return `/trash/${path}`;
  437. };
  438. pageSchema.statics.getRevertDeletedPageName = function(path) {
  439. return path.replace('/trash', '');
  440. };
  441. pageSchema.statics.isDeletableName = function(path) {
  442. const notDeletable = [
  443. /^\/user\/[^/]+$/, // user page
  444. ];
  445. for (let i = 0; i < notDeletable.length; i++) {
  446. const pattern = notDeletable[i];
  447. if (path.match(pattern)) {
  448. return false;
  449. }
  450. }
  451. return true;
  452. };
  453. pageSchema.statics.isCreatableName = function(name) {
  454. const forbiddenPages = [
  455. /\^|\$|\*|\+|#|%/,
  456. /^\/-\/.*/,
  457. /^\/_r\/.*/,
  458. /^\/_apix?(\/.*)?/,
  459. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  460. /\/{2,}/, // avoid miss in renaming
  461. /\s+\/\s+/, // avoid miss in renaming
  462. /.+\/edit$/,
  463. /.+\.md$/,
  464. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments|tags)(\/.*|$)/,
  465. ];
  466. let isCreatable = true;
  467. forbiddenPages.forEach((page) => {
  468. const pageNameReg = new RegExp(page);
  469. if (name.match(pageNameReg)) {
  470. isCreatable = false;
  471. }
  472. });
  473. return isCreatable;
  474. };
  475. pageSchema.statics.fixToCreatableName = function(path) {
  476. return path
  477. .replace(/\/\//g, '/');
  478. };
  479. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  480. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  481. cb(err, data);
  482. });
  483. };
  484. /**
  485. * return whether the user is accessible to the page
  486. * @param {string} id ObjectId
  487. * @param {User} user
  488. */
  489. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  490. const baseQuery = this.count({ _id: id });
  491. let userGroups = [];
  492. if (user != null) {
  493. validateCrowi();
  494. const UserGroupRelation = crowi.model('UserGroupRelation');
  495. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  496. }
  497. const queryBuilder = new PageQueryBuilder(baseQuery);
  498. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  499. const count = await queryBuilder.query.exec();
  500. return count > 0;
  501. };
  502. /**
  503. * @param {string} id ObjectId
  504. * @param {User} user User instance
  505. * @param {UserGroup[]} userGroups List of UserGroup instances
  506. */
  507. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups) {
  508. const baseQuery = this.findOne({ _id: id });
  509. let relatedUserGroups = userGroups;
  510. if (user != null && relatedUserGroups == null) {
  511. validateCrowi();
  512. const UserGroupRelation = crowi.model('UserGroupRelation');
  513. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  514. }
  515. const queryBuilder = new PageQueryBuilder(baseQuery);
  516. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  517. return await queryBuilder.query.exec();
  518. };
  519. // find page by path
  520. pageSchema.statics.findByPath = function(path) {
  521. if (path == null) {
  522. return null;
  523. }
  524. return this.findOne({ path });
  525. };
  526. /**
  527. * @param {string} path Page path
  528. * @param {User} user User instance
  529. * @param {UserGroup[]} userGroups List of UserGroup instances
  530. */
  531. pageSchema.statics.findByPathAndViewer = async function(path, user, userGroups) {
  532. if (path == null) {
  533. throw new Error('path is required.');
  534. }
  535. const baseQuery = this.findOne({ path });
  536. let relatedUserGroups = userGroups;
  537. if (user != null && relatedUserGroups == null) {
  538. validateCrowi();
  539. const UserGroupRelation = crowi.model('UserGroupRelation');
  540. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  541. }
  542. const queryBuilder = new PageQueryBuilder(baseQuery);
  543. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  544. return await queryBuilder.query.exec();
  545. };
  546. /**
  547. * @param {string} path Page path
  548. * @param {User} user User instance
  549. * @param {UserGroup[]} userGroups List of UserGroup instances
  550. */
  551. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups) {
  552. if (path == null) {
  553. throw new Error('path is required.');
  554. }
  555. if (path === '/') {
  556. return null;
  557. }
  558. const ancestorsPaths = extractToAncestorsPaths(path);
  559. // pick the longest one
  560. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  561. let relatedUserGroups = userGroups;
  562. if (user != null && relatedUserGroups == null) {
  563. validateCrowi();
  564. const UserGroupRelation = crowi.model('UserGroupRelation');
  565. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  566. }
  567. const queryBuilder = new PageQueryBuilder(baseQuery);
  568. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  569. return await queryBuilder.query.exec();
  570. };
  571. pageSchema.statics.findByRedirectTo = function(path) {
  572. return this.findOne({ redirectTo: path });
  573. };
  574. /**
  575. * find pages that is match with `path` and its descendants
  576. */
  577. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}) {
  578. const builder = new PageQueryBuilder(this.find());
  579. builder.addConditionToListWithDescendants(path, option);
  580. return await findListFromBuilderAndViewer(builder, user, false, option);
  581. };
  582. /**
  583. * find pages that is match with `path` and its descendants whitch user is able to manage
  584. */
  585. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}) {
  586. if (user == null) {
  587. return null;
  588. }
  589. const builder = new PageQueryBuilder(this.find());
  590. builder.addConditionToListWithDescendants(page.path, option);
  591. builder.addConditionToExcludeRedirect();
  592. // add grant conditions
  593. await addConditionToFilteringByViewerToEdit(builder, user);
  594. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  595. // add page if 'grant' is GRANT_RESTRICTED
  596. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  597. if (page.grant === GRANT_RESTRICTED) {
  598. pages.push(page);
  599. }
  600. return pages;
  601. };
  602. /**
  603. * find pages that start with `path`
  604. */
  605. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  606. const builder = new PageQueryBuilder(this.find());
  607. builder.addConditionToListByStartWith(path, option);
  608. return await findListFromBuilderAndViewer(builder, user, false, option);
  609. };
  610. /**
  611. * find pages that is created by targetUser
  612. *
  613. * @param {User} targetUser
  614. * @param {User} currentUser
  615. * @param {any} option
  616. */
  617. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  618. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  619. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  620. let showAnyoneKnowsLink = null;
  621. if (targetUser != null && currentUser != null) {
  622. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  623. }
  624. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  625. };
  626. pageSchema.statics.findListByPageIds = async function(ids, option) {
  627. const User = crowi.model('User');
  628. const opt = Object.assign({}, option);
  629. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  630. builder.addConditionToExcludeRedirect();
  631. builder.addConditionToPagenate(opt.offset, opt.limit);
  632. // count
  633. const totalCount = await builder.query.exec('count');
  634. // find
  635. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  636. const pages = await builder.query.exec('find');
  637. const result = {
  638. pages, totalCount, offset: opt.offset, limit: opt.limit,
  639. };
  640. return result;
  641. };
  642. /**
  643. * find pages by PageQueryBuilder
  644. * @param {PageQueryBuilder} builder
  645. * @param {User} user
  646. * @param {boolean} showAnyoneKnowsLink
  647. * @param {any} option
  648. */
  649. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  650. validateCrowi();
  651. const User = crowi.model('User');
  652. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  653. const sortOpt = {};
  654. sortOpt[opt.sort] = opt.desc;
  655. // exclude trashed pages
  656. if (!opt.includeTrashed) {
  657. builder.addConditionToExcludeTrashed();
  658. }
  659. // exclude redirect pages
  660. if (!opt.includeRedirect) {
  661. builder.addConditionToExcludeRedirect();
  662. }
  663. // add grant conditions
  664. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  665. // count
  666. const totalCount = await builder.query.exec('count');
  667. // find
  668. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  669. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  670. const pages = await builder.query.exec('find');
  671. const result = {
  672. pages, totalCount, offset: opt.offset, limit: opt.limit,
  673. };
  674. return result;
  675. }
  676. /**
  677. * Add condition that filter pages by viewer
  678. * by considering Config
  679. *
  680. * @param {PageQueryBuilder} builder
  681. * @param {User} user
  682. * @param {boolean} showAnyoneKnowsLink
  683. */
  684. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  685. validateCrowi();
  686. // determine User condition
  687. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  688. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  689. // determine UserGroup condition
  690. let userGroups = null;
  691. if (user != null) {
  692. const UserGroupRelation = crowi.model('UserGroupRelation');
  693. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  694. }
  695. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  696. }
  697. /**
  698. * Add condition that filter pages by viewer
  699. * by considering Config
  700. *
  701. * @param {PageQueryBuilder} builder
  702. * @param {User} user
  703. * @param {boolean} showAnyoneKnowsLink
  704. */
  705. async function addConditionToFilteringByViewerToEdit(builder, user) {
  706. validateCrowi();
  707. // determine UserGroup condition
  708. let userGroups = null;
  709. if (user != null) {
  710. const UserGroupRelation = crowi.model('UserGroupRelation');
  711. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  712. }
  713. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  714. }
  715. /**
  716. * export addConditionToFilteringByViewerForList as static method
  717. */
  718. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  719. /**
  720. * Throw error for growi-lsx-plugin (v1.x)
  721. */
  722. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  723. const dummyQuery = this.find();
  724. dummyQuery.exec = async() => {
  725. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  726. };
  727. return dummyQuery;
  728. };
  729. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  730. /**
  731. * find all templates applicable to the new page
  732. */
  733. pageSchema.statics.findTemplate = async function(path) {
  734. const templatePath = nodePath.posix.dirname(path);
  735. const pathList = generatePathsOnTree(path, []);
  736. const regexpList = pathList.map((path) => {
  737. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  738. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  739. });
  740. const templatePages = await this.find({ path: { $in: regexpList } })
  741. .populate({ path: 'revision', model: 'Revision' })
  742. .exec();
  743. return fetchTemplate(templatePages, templatePath);
  744. };
  745. const generatePathsOnTree = (path, pathList) => {
  746. pathList.push(path);
  747. if (path === '/') {
  748. return pathList;
  749. }
  750. const newPath = nodePath.posix.dirname(path);
  751. return generatePathsOnTree(newPath, pathList);
  752. };
  753. const assignTemplateByType = (templates, path, type) => {
  754. const targetTemplatePath = urljoin(path, `${type}template`);
  755. return templates.find((template) => {
  756. return (template.path === targetTemplatePath);
  757. });
  758. };
  759. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  760. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  761. if (decendantsTemplate) {
  762. return decendantsTemplate;
  763. }
  764. if (path === '/') {
  765. return;
  766. }
  767. const newPath = nodePath.posix.dirname(path);
  768. return assignDecendantsTemplate(decendantsTemplates, newPath);
  769. };
  770. const fetchTemplate = async(templates, templatePath) => {
  771. let templateBody;
  772. let templateTags;
  773. /**
  774. * get children template
  775. * __tempate: applicable only to immediate decendants
  776. */
  777. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  778. /**
  779. * get decendants templates
  780. * _tempate: applicable to all pages under
  781. */
  782. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  783. if (childrenTemplate) {
  784. templateBody = childrenTemplate.revision.body;
  785. templateTags = await childrenTemplate.findRelatedTagsById();
  786. }
  787. else if (decendantsTemplate) {
  788. templateBody = decendantsTemplate.revision.body;
  789. templateTags = await decendantsTemplate.findRelatedTagsById();
  790. }
  791. return { templateBody, templateTags };
  792. };
  793. async function pushRevision(pageData, newRevision, user) {
  794. await newRevision.save();
  795. debug('Successfully saved new revision', newRevision);
  796. pageData.revision = newRevision;
  797. pageData.lastUpdateUser = user;
  798. pageData.updatedAt = Date.now();
  799. return pageData.save();
  800. }
  801. async function validateAppliedScope(user, grant, grantUserGroupId) {
  802. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  803. throw new Error('grant userGroupId is not specified');
  804. }
  805. if (grant === GRANT_USER_GROUP) {
  806. const UserGroupRelation = crowi.model('UserGroupRelation');
  807. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  808. if (count === 0) {
  809. throw new Error('no relations were exist for group and user.');
  810. }
  811. }
  812. }
  813. pageSchema.statics.create = async function(path, body, user, options = {}) {
  814. validateCrowi();
  815. const Page = this;
  816. const Revision = crowi.model('Revision');
  817. const format = options.format || 'markdown';
  818. const redirectTo = options.redirectTo || null;
  819. const grantUserGroupId = options.grantUserGroupId || null;
  820. const socketClientId = options.socketClientId || null;
  821. // sanitize path
  822. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  823. let grant = options.grant;
  824. // force public
  825. if (isTopPage(path)) {
  826. grant = GRANT_PUBLIC;
  827. }
  828. const isExist = await this.count({ path });
  829. if (isExist) {
  830. throw new Error('Cannot create new page to existed path');
  831. }
  832. const page = new Page();
  833. page.path = path;
  834. page.creator = user;
  835. page.lastUpdateUser = user;
  836. page.redirectTo = redirectTo;
  837. page.status = STATUS_PUBLISHED;
  838. await validateAppliedScope(user, grant, grantUserGroupId);
  839. page.applyScope(user, grant, grantUserGroupId);
  840. let savedPage = await page.save();
  841. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  842. const revision = await pushRevision(savedPage, newRevision, user);
  843. savedPage = await this.findByPath(revision.path);
  844. await savedPage.populateDataToShowRevision();
  845. if (socketClientId != null) {
  846. pageEvent.emit('create', savedPage, user, socketClientId);
  847. }
  848. return savedPage;
  849. };
  850. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  851. validateCrowi();
  852. const Revision = crowi.model('Revision');
  853. const grant = options.grant || pageData.grant; // use the previous data if absence
  854. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  855. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  856. const socketClientId = options.socketClientId || null;
  857. await validateAppliedScope(user, grant, grantUserGroupId);
  858. pageData.applyScope(user, grant, grantUserGroupId);
  859. // update existing page
  860. let savedPage = await pageData.save();
  861. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  862. const revision = await pushRevision(savedPage, newRevision, user);
  863. savedPage = await this.findByPath(revision.path);
  864. await savedPage.populateDataToShowRevision();
  865. if (isSyncRevisionToHackmd) {
  866. savedPage = await this.syncRevisionToHackmd(savedPage);
  867. }
  868. if (socketClientId != null) {
  869. pageEvent.emit('update', savedPage, user, socketClientId);
  870. }
  871. return savedPage;
  872. };
  873. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  874. const builder = new PageQueryBuilder(this.find());
  875. builder.addConditionToListWithDescendants(parentPage.path);
  876. builder.addConditionToExcludeRedirect();
  877. // add grant conditions
  878. await addConditionToFilteringByViewerToEdit(builder, user);
  879. // get all pages that the specified user can update
  880. const pages = await builder.query.exec();
  881. for (const page of pages) {
  882. // skip parentPage
  883. if (page.id === parentPage.id) {
  884. continue;
  885. }
  886. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  887. page.save();
  888. }
  889. };
  890. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  891. const newPath = this.getDeletedPageName(pageData.path);
  892. const isTrashed = checkIfTrashed(pageData.path);
  893. if (isTrashed) {
  894. throw new Error('This method does NOT support deleting trashed pages.');
  895. }
  896. const socketClientId = options.socketClientId || null;
  897. if (this.isDeletableName(pageData.path)) {
  898. pageData.status = STATUS_DELETED;
  899. const updatedPageData = await this.rename(pageData, newPath, user, { socketClientId, createRedirectPage: true });
  900. return updatedPageData;
  901. }
  902. return Promise.reject(new Error('Page is not deletable.'));
  903. };
  904. const checkIfTrashed = (path) => {
  905. return (path.search(/^\/trash/) !== -1);
  906. };
  907. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  908. const isTrashed = checkIfTrashed(targetPage.path);
  909. if (isTrashed) {
  910. throw new Error('This method does NOT supports deleting trashed pages.');
  911. }
  912. // find manageable descendants (this array does not include GRANT_RESTRICTED)
  913. const pages = await this.findManageableListWithDescendants(targetPage, user, options);
  914. await Promise.all(pages.map((page) => {
  915. return this.deletePage(page, user, options);
  916. }));
  917. };
  918. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  919. const newPath = this.getRevertDeletedPageName(page.path);
  920. const originPage = await this.findByPath(newPath);
  921. if (originPage != null) {
  922. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  923. // そのため、そいつは削除してOK
  924. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  925. if (originPage.redirectTo !== page.path) {
  926. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  927. }
  928. await this.completelyDeletePage(originPage, options);
  929. }
  930. page.status = STATUS_PUBLISHED;
  931. page.lastUpdateUser = user;
  932. debug('Revert deleted the page', page, newPath);
  933. const updatedPage = await this.rename(page, newPath, user, {});
  934. return updatedPage;
  935. };
  936. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  937. const findOpts = { includeTrashed: true };
  938. const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
  939. let updatedPage = null;
  940. await Promise.all(pages.map((page) => {
  941. const isParent = (page.path === targetPage.path);
  942. const p = this.revertDeletedPage(page, user, options);
  943. if (isParent) {
  944. updatedPage = p;
  945. }
  946. return p;
  947. }));
  948. return updatedPage;
  949. };
  950. /**
  951. * This is danger.
  952. */
  953. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  954. validateCrowi();
  955. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  956. const Bookmark = crowi.model('Bookmark');
  957. const Attachment = crowi.model('Attachment');
  958. const Comment = crowi.model('Comment');
  959. const PageTagRelation = crowi.model('PageTagRelation');
  960. const Revision = crowi.model('Revision');
  961. const pageId = pageData._id;
  962. const socketClientId = options.socketClientId || null;
  963. debug('Completely delete', pageData.path);
  964. await Bookmark.removeBookmarksByPageId(pageId);
  965. await Attachment.removeAttachmentsByPageId(pageId);
  966. await Comment.removeCommentsByPageId(pageId);
  967. await PageTagRelation.remove({ relatedPage: pageId });
  968. await Revision.removeRevisionsByPath(pageData.path);
  969. await this.findByIdAndRemove(pageId);
  970. await this.removeRedirectOriginPageByPath(pageData.path);
  971. if (socketClientId != null) {
  972. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  973. }
  974. return pageData;
  975. };
  976. /**
  977. * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  978. */
  979. pageSchema.statics.completelyDeletePageRecursively = async function(targetPage, user, options = {}) {
  980. const findOpts = { includeTrashed: true };
  981. // find manageable descendants (this array does not include GRANT_RESTRICTED)
  982. const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
  983. await Promise.all(pages.map((page) => {
  984. return this.completelyDeletePage(page, user, options);
  985. }));
  986. };
  987. pageSchema.statics.removeByPath = function(path) {
  988. if (path == null) {
  989. throw new Error('path is required');
  990. }
  991. return this.findOneAndRemove({ path }).exec();
  992. };
  993. /**
  994. * remove the page that is redirecting to specified `pagePath` recursively
  995. * ex: when
  996. * '/page1' redirects to '/page2' and
  997. * '/page2' redirects to '/page3'
  998. * and given '/page3',
  999. * '/page1' and '/page2' will be removed
  1000. *
  1001. * @param {string} pagePath
  1002. */
  1003. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  1004. const redirectPage = await this.findByRedirectTo(pagePath);
  1005. if (redirectPage == null) {
  1006. return;
  1007. }
  1008. // remove
  1009. await this.findByIdAndRemove(redirectPage.id);
  1010. // remove recursive
  1011. await this.removeRedirectOriginPageByPath(redirectPage.path);
  1012. };
  1013. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1014. validateCrowi();
  1015. const Page = this;
  1016. const Revision = crowi.model('Revision');
  1017. const path = pageData.path;
  1018. const createRedirectPage = options.createRedirectPage || false;
  1019. const updateMetadata = options.updateMetadata || false;
  1020. const socketClientId = options.socketClientId || null;
  1021. // sanitize path
  1022. newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  1023. // update Page
  1024. pageData.path = newPagePath;
  1025. if (updateMetadata) {
  1026. pageData.lastUpdateUser = user;
  1027. pageData.updatedAt = Date.now();
  1028. }
  1029. const updatedPageData = await pageData.save();
  1030. // update Rivisions
  1031. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  1032. if (createRedirectPage) {
  1033. const body = `redirect ${newPagePath}`;
  1034. await Page.create(path, body, user, { redirectTo: newPagePath });
  1035. }
  1036. pageEvent.emit('delete', pageData, user, socketClientId);
  1037. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1038. return updatedPageData;
  1039. };
  1040. pageSchema.statics.renameRecursively = async function(targetPage, newPagePathPrefix, user, options) {
  1041. validateCrowi();
  1042. const path = targetPage.path;
  1043. const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
  1044. // sanitize path
  1045. newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
  1046. // find manageable descendants
  1047. const pages = await this.findManageableListWithDescendants(targetPage, user, options);
  1048. await Promise.all(pages.map((page) => {
  1049. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1050. return this.rename(page, newPagePath, user, options);
  1051. }));
  1052. targetPage.path = newPagePathPrefix;
  1053. return targetPage;
  1054. };
  1055. pageSchema.statics.handlePrivatePagesForDeletedGroup = async function(deletedGroup, action, transferToUserGroupId) {
  1056. const Page = mongoose.model('Page');
  1057. const pages = await this.find({ grantedGroup: deletedGroup });
  1058. switch (action) {
  1059. case 'public':
  1060. await Promise.all(pages.map((page) => {
  1061. return Page.publicizePage(page);
  1062. }));
  1063. break;
  1064. case 'delete':
  1065. await Promise.all(pages.map((page) => {
  1066. return Page.completelyDeletePage(page);
  1067. }));
  1068. break;
  1069. case 'transfer':
  1070. await Promise.all(pages.map((page) => {
  1071. return Page.transferPageToGroup(page, transferToUserGroupId);
  1072. }));
  1073. break;
  1074. default:
  1075. throw new Error('Unknown action for private pages');
  1076. }
  1077. };
  1078. pageSchema.statics.publicizePage = async function(page) {
  1079. page.grantedGroup = null;
  1080. page.grant = GRANT_PUBLIC;
  1081. await page.save();
  1082. };
  1083. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  1084. const UserGroup = mongoose.model('UserGroup');
  1085. // check page existence
  1086. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  1087. if (isExist) {
  1088. page.grantedGroup = transferToUserGroupId;
  1089. await page.save();
  1090. }
  1091. else {
  1092. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  1093. }
  1094. };
  1095. /**
  1096. * associate GROWI page and HackMD page
  1097. * @param {Page} pageData
  1098. * @param {string} pageIdOnHackmd
  1099. */
  1100. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1101. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1102. return this.syncRevisionToHackmd(pageData);
  1103. };
  1104. /**
  1105. * update revisionHackmdSynced
  1106. * @param {Page} pageData
  1107. * @param {bool} isSave whether save or not
  1108. */
  1109. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1110. pageData.revisionHackmdSynced = pageData.revision;
  1111. pageData.hasDraftOnHackmd = false;
  1112. let returnData = pageData;
  1113. if (isSave) {
  1114. returnData = pageData.save();
  1115. }
  1116. return returnData;
  1117. };
  1118. /**
  1119. * update hasDraftOnHackmd
  1120. * !! This will be invoked many time from many people !!
  1121. *
  1122. * @param {Page} pageData
  1123. * @param {Boolean} newValue
  1124. */
  1125. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1126. if (pageData.hasDraftOnHackmd === newValue) {
  1127. // do nothing when hasDraftOnHackmd equals to newValue
  1128. return;
  1129. }
  1130. pageData.hasDraftOnHackmd = newValue;
  1131. return pageData.save();
  1132. };
  1133. pageSchema.statics.getHistories = function() {
  1134. // TODO
  1135. };
  1136. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1137. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1138. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1139. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1140. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1141. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1142. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1143. return mongoose.model('Page', pageSchema);
  1144. };