page.js 40 KB

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