page.js 40 KB

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