page.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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 start with `path`
  584. */
  585. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  586. const builder = new PageQueryBuilder(this.find());
  587. builder.addConditionToListByStartWith(path, option);
  588. return await findListFromBuilderAndViewer(builder, user, false, option);
  589. };
  590. /**
  591. * find pages that is created by targetUser
  592. *
  593. * @param {User} targetUser
  594. * @param {User} currentUser
  595. * @param {any} option
  596. */
  597. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  598. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  599. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  600. let showAnyoneKnowsLink = null;
  601. if (targetUser != null && currentUser != null) {
  602. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  603. }
  604. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  605. };
  606. pageSchema.statics.findListByPageIds = async function(ids, option) {
  607. const User = crowi.model('User');
  608. const opt = Object.assign({}, option);
  609. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  610. builder.addConditionToExcludeRedirect();
  611. builder.addConditionToPagenate(opt.offset, opt.limit);
  612. // count
  613. const totalCount = await builder.query.exec('count');
  614. // find
  615. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  616. const pages = await builder.query.exec('find');
  617. const result = {
  618. pages, totalCount, offset: opt.offset, limit: opt.limit,
  619. };
  620. return result;
  621. };
  622. /**
  623. * find pages by PageQueryBuilder
  624. * @param {PageQueryBuilder} builder
  625. * @param {User} user
  626. * @param {boolean} showAnyoneKnowsLink
  627. * @param {any} option
  628. */
  629. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  630. validateCrowi();
  631. const User = crowi.model('User');
  632. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  633. const sortOpt = {};
  634. sortOpt[opt.sort] = opt.desc;
  635. // exclude trashed pages
  636. if (!opt.includeTrashed) {
  637. builder.addConditionToExcludeTrashed();
  638. }
  639. // exclude redirect pages
  640. if (!opt.includeRedirect) {
  641. builder.addConditionToExcludeRedirect();
  642. }
  643. // add grant conditions
  644. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  645. // count
  646. const totalCount = await builder.query.exec('count');
  647. // find
  648. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  649. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  650. const pages = await builder.query.exec('find');
  651. const result = {
  652. pages, totalCount, offset: opt.offset, limit: opt.limit,
  653. };
  654. return result;
  655. }
  656. /**
  657. * Add condition that filter pages by viewer
  658. * by considering Config
  659. *
  660. * @param {PageQueryBuilder} builder
  661. * @param {User} user
  662. * @param {boolean} showAnyoneKnowsLink
  663. */
  664. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  665. validateCrowi();
  666. // determine User condition
  667. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  668. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  669. // determine UserGroup condition
  670. let userGroups = null;
  671. if (user != null) {
  672. const UserGroupRelation = crowi.model('UserGroupRelation');
  673. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  674. }
  675. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  676. }
  677. /**
  678. * Add condition that filter pages by viewer
  679. * by considering Config
  680. *
  681. * @param {PageQueryBuilder} builder
  682. * @param {User} user
  683. * @param {boolean} showAnyoneKnowsLink
  684. */
  685. async function addConditionToFilteringByViewerToEdit(builder, user) {
  686. validateCrowi();
  687. // determine UserGroup condition
  688. let userGroups = null;
  689. if (user != null) {
  690. const UserGroupRelation = crowi.model('UserGroupRelation');
  691. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  692. }
  693. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  694. }
  695. /**
  696. * export addConditionToFilteringByViewerForList as static method
  697. */
  698. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  699. /**
  700. * Throw error for growi-lsx-plugin (v1.x)
  701. */
  702. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  703. const dummyQuery = this.find();
  704. dummyQuery.exec = async() => {
  705. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  706. };
  707. return dummyQuery;
  708. };
  709. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  710. /**
  711. * find all templates applicable to the new page
  712. */
  713. pageSchema.statics.findTemplate = async function(path) {
  714. const templatePath = nodePath.posix.dirname(path);
  715. const pathList = generatePathsOnTree(path, []);
  716. const regexpList = pathList.map((path) => {
  717. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  718. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  719. });
  720. const templatePages = await this.find({ path: { $in: regexpList } })
  721. .populate({ path: 'revision', model: 'Revision' })
  722. .exec();
  723. return fetchTemplate(templatePages, templatePath);
  724. };
  725. const generatePathsOnTree = (path, pathList) => {
  726. pathList.push(path);
  727. if (path === '/') {
  728. return pathList;
  729. }
  730. const newPath = nodePath.posix.dirname(path);
  731. return generatePathsOnTree(newPath, pathList);
  732. };
  733. const assignTemplateByType = (templates, path, type) => {
  734. const targetTemplatePath = urljoin(path, `${type}template`);
  735. return templates.find((template) => {
  736. return (template.path === targetTemplatePath);
  737. });
  738. };
  739. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  740. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  741. if (decendantsTemplate) {
  742. return decendantsTemplate;
  743. }
  744. if (path === '/') {
  745. return;
  746. }
  747. const newPath = nodePath.posix.dirname(path);
  748. return assignDecendantsTemplate(decendantsTemplates, newPath);
  749. };
  750. const fetchTemplate = async(templates, templatePath) => {
  751. let templateBody;
  752. let templateTags;
  753. /**
  754. * get children template
  755. * __tempate: applicable only to immediate decendants
  756. */
  757. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  758. /**
  759. * get decendants templates
  760. * _tempate: applicable to all pages under
  761. */
  762. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  763. if (childrenTemplate) {
  764. templateBody = childrenTemplate.revision.body;
  765. templateTags = await childrenTemplate.findRelatedTagsById();
  766. }
  767. else if (decendantsTemplate) {
  768. templateBody = decendantsTemplate.revision.body;
  769. templateTags = await decendantsTemplate.findRelatedTagsById();
  770. }
  771. return { templateBody, templateTags };
  772. };
  773. async function pushRevision(pageData, newRevision, user) {
  774. await newRevision.save();
  775. debug('Successfully saved new revision', newRevision);
  776. pageData.revision = newRevision;
  777. pageData.lastUpdateUser = user;
  778. pageData.updatedAt = Date.now();
  779. return pageData.save();
  780. }
  781. async function validateAppliedScope(user, grant, grantUserGroupId) {
  782. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  783. throw new Error('grant userGroupId is not specified');
  784. }
  785. if (grant === GRANT_USER_GROUP) {
  786. const UserGroupRelation = crowi.model('UserGroupRelation');
  787. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  788. if (count === 0) {
  789. throw new Error('no relations were exist for group and user.');
  790. }
  791. }
  792. }
  793. pageSchema.statics.create = async function(path, body, user, options = {}) {
  794. validateCrowi();
  795. const Page = this;
  796. const Revision = crowi.model('Revision');
  797. const format = options.format || 'markdown';
  798. const redirectTo = options.redirectTo || null;
  799. const grantUserGroupId = options.grantUserGroupId || null;
  800. const socketClientId = options.socketClientId || null;
  801. // sanitize path
  802. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  803. let grant = options.grant;
  804. // force public
  805. if (isTopPage(path)) {
  806. grant = GRANT_PUBLIC;
  807. }
  808. const isExist = await this.count({ path });
  809. if (isExist) {
  810. throw new Error('Cannot create new page to existed path');
  811. }
  812. const page = new Page();
  813. page.path = path;
  814. page.creator = user;
  815. page.lastUpdateUser = user;
  816. page.redirectTo = redirectTo;
  817. page.status = STATUS_PUBLISHED;
  818. await validateAppliedScope(user, grant, grantUserGroupId);
  819. page.applyScope(user, grant, grantUserGroupId);
  820. let savedPage = await page.save();
  821. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  822. const revision = await pushRevision(savedPage, newRevision, user);
  823. savedPage = await this.findByPath(revision.path);
  824. await savedPage.populateDataToShowRevision();
  825. if (socketClientId != null) {
  826. pageEvent.emit('create', savedPage, user, socketClientId);
  827. }
  828. return savedPage;
  829. };
  830. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  831. validateCrowi();
  832. const Revision = crowi.model('Revision');
  833. const grant = options.grant || pageData.grant; // use the previous data if absence
  834. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  835. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  836. const socketClientId = options.socketClientId || null;
  837. await validateAppliedScope(user, grant, grantUserGroupId);
  838. pageData.applyScope(user, grant, grantUserGroupId);
  839. // update existing page
  840. let savedPage = await pageData.save();
  841. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  842. const revision = await pushRevision(savedPage, newRevision, user);
  843. savedPage = await this.findByPath(revision.path);
  844. await savedPage.populateDataToShowRevision();
  845. if (isSyncRevisionToHackmd) {
  846. savedPage = await this.syncRevisionToHackmd(savedPage);
  847. }
  848. if (socketClientId != null) {
  849. pageEvent.emit('update', savedPage, user, socketClientId);
  850. }
  851. return savedPage;
  852. };
  853. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  854. const builder = new PageQueryBuilder(this.find());
  855. builder.addConditionToListWithDescendants(parentPage.path);
  856. builder.addConditionToExcludeRedirect();
  857. // add grant conditions
  858. await addConditionToFilteringByViewerToEdit(builder, user);
  859. // get all pages that the specified user can update
  860. const pages = await builder.query.exec();
  861. for (const page of pages) {
  862. // skip parentPage
  863. if (page.id === parentPage.id) {
  864. continue;
  865. }
  866. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  867. page.save();
  868. }
  869. };
  870. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  871. const newPath = this.getDeletedPageName(pageData.path);
  872. const isTrashed = checkIfTrashed(pageData.path);
  873. if (isTrashed) {
  874. throw new Error('This method does NOT support deleting trashed pages.');
  875. }
  876. const socketClientId = options.socketClientId || null;
  877. if (this.isDeletableName(pageData.path)) {
  878. pageData.status = STATUS_DELETED;
  879. const updatedPageData = await this.rename(pageData, newPath, user, { socketClientId, createRedirectPage: true });
  880. return updatedPageData;
  881. }
  882. return Promise.reject(new Error('Page is not deletable.'));
  883. };
  884. const checkIfTrashed = (path) => {
  885. return (path.search(/^\/trash/) !== -1);
  886. };
  887. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  888. const isTrashed = checkIfTrashed(targetPage.path);
  889. if (isTrashed) {
  890. throw new Error('This method does NOT supports deleting trashed pages.');
  891. }
  892. // find descendants (this array does not include GRANT_RESTRICTED)
  893. const result = await this.findListWithDescendants(targetPage.path, user);
  894. const pages = result.pages;
  895. // add targetPage if 'grant' is GRANT_RESTRICTED
  896. // because findListWithDescendants excludes GRANT_RESTRICTED pages
  897. if (targetPage.grant === GRANT_RESTRICTED) {
  898. pages.push(targetPage);
  899. }
  900. await Promise.all(pages.map((page) => {
  901. return this.deletePage(page, user, options);
  902. }));
  903. };
  904. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  905. const newPath = this.getRevertDeletedPageName(page.path);
  906. const originPage = await this.findByPath(newPath);
  907. if (originPage != null) {
  908. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  909. // そのため、そいつは削除してOK
  910. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  911. if (originPage.redirectTo !== page.path) {
  912. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  913. }
  914. await this.completelyDeletePage(originPage, options);
  915. }
  916. page.status = STATUS_PUBLISHED;
  917. page.lastUpdateUser = user;
  918. debug('Revert deleted the page', page, newPath);
  919. const updatedPage = await this.rename(page, newPath, user, {});
  920. return updatedPage;
  921. };
  922. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  923. const findOpts = { includeTrashed: true };
  924. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  925. const pages = result.pages;
  926. let updatedPage = null;
  927. await Promise.all(pages.map((page) => {
  928. const isParent = (page.path === targetPage.path);
  929. const p = this.revertDeletedPage(page, user, options);
  930. if (isParent) {
  931. updatedPage = p;
  932. }
  933. return p;
  934. }));
  935. return updatedPage;
  936. };
  937. /**
  938. * This is danger.
  939. */
  940. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  941. validateCrowi();
  942. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  943. const Bookmark = crowi.model('Bookmark');
  944. const Attachment = crowi.model('Attachment');
  945. const Comment = crowi.model('Comment');
  946. const PageTagRelation = crowi.model('PageTagRelation');
  947. const Revision = crowi.model('Revision');
  948. const pageId = pageData._id;
  949. const socketClientId = options.socketClientId || null;
  950. debug('Completely delete', pageData.path);
  951. await Bookmark.removeBookmarksByPageId(pageId);
  952. await Attachment.removeAttachmentsByPageId(pageId);
  953. await Comment.removeCommentsByPageId(pageId);
  954. await PageTagRelation.remove({ relatedPage: pageId });
  955. await Revision.removeRevisionsByPath(pageData.path);
  956. await this.findByIdAndRemove(pageId);
  957. await this.removeRedirectOriginPageByPath(pageData.path);
  958. if (socketClientId != null) {
  959. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  960. }
  961. return pageData;
  962. };
  963. /**
  964. * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  965. */
  966. pageSchema.statics.completelyDeletePageRecursively = async function(targetPage, user, options = {}) {
  967. const pagePath = targetPage.path;
  968. const findOpts = { includeTrashed: true };
  969. // find descendants (this array does not include GRANT_RESTRICTED)
  970. const result = await this.findListWithDescendants(pagePath, user, findOpts);
  971. const pages = result.pages;
  972. // add targetPage if 'grant' is GRANT_RESTRICTED
  973. // because findListWithDescendants excludes GRANT_RESTRICTED pages
  974. if (targetPage.grant === GRANT_RESTRICTED) {
  975. pages.push(targetPage);
  976. }
  977. await Promise.all(pages.map((page) => {
  978. return this.completelyDeletePage(page, user, options);
  979. }));
  980. };
  981. pageSchema.statics.removeByPath = function(path) {
  982. if (path == null) {
  983. throw new Error('path is required');
  984. }
  985. return this.findOneAndRemove({ path }).exec();
  986. };
  987. /**
  988. * remove the page that is redirecting to specified `pagePath` recursively
  989. * ex: when
  990. * '/page1' redirects to '/page2' and
  991. * '/page2' redirects to '/page3'
  992. * and given '/page3',
  993. * '/page1' and '/page2' will be removed
  994. *
  995. * @param {string} pagePath
  996. */
  997. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  998. const redirectPage = await this.findByRedirectTo(pagePath);
  999. if (redirectPage == null) {
  1000. return;
  1001. }
  1002. // remove
  1003. await this.findByIdAndRemove(redirectPage.id);
  1004. // remove recursive
  1005. await this.removeRedirectOriginPageByPath(redirectPage.path);
  1006. };
  1007. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1008. validateCrowi();
  1009. const Page = this;
  1010. const Revision = crowi.model('Revision');
  1011. const path = pageData.path;
  1012. const createRedirectPage = options.createRedirectPage || false;
  1013. const updateMetadata = options.updateMetadata || false;
  1014. const socketClientId = options.socketClientId || null;
  1015. // sanitize path
  1016. newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  1017. // update Page
  1018. pageData.path = newPagePath;
  1019. if (updateMetadata) {
  1020. pageData.lastUpdateUser = user;
  1021. pageData.updatedAt = Date.now();
  1022. }
  1023. const updatedPageData = await pageData.save();
  1024. // update Rivisions
  1025. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  1026. if (createRedirectPage) {
  1027. const body = `redirect ${newPagePath}`;
  1028. await Page.create(path, body, user, { redirectTo: newPagePath });
  1029. }
  1030. pageEvent.emit('delete', pageData, user, socketClientId);
  1031. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1032. return updatedPageData;
  1033. };
  1034. pageSchema.statics.renameRecursively = async function(targetPage, newPagePathPrefix, user, options) {
  1035. validateCrowi();
  1036. const path = targetPage.path;
  1037. const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
  1038. // sanitize path
  1039. newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
  1040. // find descendants (this array does not include GRANT_RESTRICTED)
  1041. const result = await this.findListWithDescendants(path, user, options);
  1042. const pages = result.pages;
  1043. // add targetPage if 'grant' is GRANT_RESTRICTED
  1044. // because findListWithDescendants excludes GRANT_RESTRICTED pages
  1045. if (targetPage.grant === GRANT_RESTRICTED) {
  1046. pages.push(targetPage);
  1047. }
  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. };