page.js 37 KB

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