page.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  332. /\/{2,}/, // avoid miss in renaming
  333. /\s+\/\s+/, // avoid miss in renaming
  334. /.+\/edit$/,
  335. /.+\.md$/,
  336. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  337. ];
  338. var isCreatable = true;
  339. forbiddenPages.forEach(function(page) {
  340. var pageNameReg = new RegExp(page);
  341. if (name.match(pageNameReg)) {
  342. isCreatable = false;
  343. return ;
  344. }
  345. });
  346. return isCreatable;
  347. };
  348. pageSchema.statics.fixToCreatableName = function(path) {
  349. return path
  350. .replace(/\/\//g, '/')
  351. ;
  352. };
  353. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  354. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  355. cb(err, data);
  356. });
  357. };
  358. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  359. this
  360. .find({})
  361. .sort({updatedAt: -1})
  362. .skip(offset)
  363. .limit(limit)
  364. .exec(function(err, data) {
  365. cb(err, data);
  366. });
  367. };
  368. pageSchema.statics.findPageById = function(id) {
  369. var Page = this;
  370. return new Promise(function(resolve, reject) {
  371. Page.findOne({_id: id}, function(err, pageData) {
  372. if (err) {
  373. return reject(err);
  374. }
  375. if (pageData == null) {
  376. return reject(new Error('Page not found'));
  377. }
  378. return Page.populatePageData(pageData, null).then(resolve);
  379. });
  380. });
  381. };
  382. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  383. var Page = this;
  384. var PageGroupRelation = crowi.model('PageGroupRelation');
  385. var pageData = null;
  386. return new Promise(function(resolve, reject) {
  387. Page.findPageById(id)
  388. .then(function(result) {
  389. pageData = result;
  390. if (userData && !pageData.isGrantedFor(userData)) {
  391. return PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData);
  392. }
  393. else {
  394. return true;
  395. }
  396. }).then((checkResult) => {
  397. if (checkResult) {
  398. return resolve(pageData);
  399. }
  400. else {
  401. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  402. }
  403. }).catch(function(err) {
  404. return reject(err);
  405. });
  406. });
  407. };
  408. // find page and check if granted user
  409. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  410. var self = this;
  411. var PageGroupRelation = crowi.model('PageGroupRelation');
  412. return new Promise(function(resolve, reject) {
  413. self.findOne({path: path}, function(err, pageData) {
  414. if (err) {
  415. return reject(err);
  416. }
  417. if (pageData === null) {
  418. if (ignoreNotFound) {
  419. return resolve(null);
  420. }
  421. var pageNotFoundError = new Error('Page Not Found')
  422. pageNotFoundError.name = 'Crowi:Page:NotFound';
  423. return reject(pageNotFoundError);
  424. }
  425. if (!pageData.isGrantedFor(userData)) {
  426. PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData)
  427. .then(function (checkResult) {
  428. if (!checkResult) {
  429. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  430. } else {
  431. // return resolve(pageData);
  432. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  433. }
  434. })
  435. .catch(function (err) {
  436. return reject(err);
  437. });
  438. }
  439. else {
  440. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  441. }
  442. });
  443. });
  444. };
  445. // find page by path
  446. pageSchema.statics.findPageByPath = function(path) {
  447. var Page = this;
  448. return new Promise(function(resolve, reject) {
  449. Page.findOne({path: path}, function(err, pageData) {
  450. if (err || pageData === null) {
  451. return reject(err);
  452. }
  453. return resolve(pageData);
  454. });
  455. });
  456. };
  457. pageSchema.statics.findListByPageIds = function(ids, options) {
  458. var Page = this;
  459. var User = crowi.model('User');
  460. var options = options || {}
  461. , limit = options.limit || 50
  462. , offset = options.skip || 0
  463. ;
  464. return new Promise(function(resolve, reject) {
  465. Page
  466. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  467. //.sort({createdAt: -1}) // TODO optionize
  468. .skip(offset)
  469. .limit(limit)
  470. .populate([
  471. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  472. {path: 'revision', model: 'Revision'},
  473. ])
  474. .exec(function(err, pages) {
  475. if (err) {
  476. return reject(err);
  477. }
  478. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  479. if (err) {
  480. return reject(err);
  481. }
  482. return resolve(data);
  483. });
  484. });
  485. });
  486. };
  487. pageSchema.statics.findPageByRedirectTo = function(path) {
  488. var Page = this;
  489. return new Promise(function(resolve, reject) {
  490. Page.findOne({redirectTo: path}, function(err, pageData) {
  491. if (err || pageData === null) {
  492. return reject(err);
  493. }
  494. return resolve(pageData);
  495. });
  496. });
  497. };
  498. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  499. var Page = this;
  500. var User = crowi.model('User');
  501. var limit = option.limit || 50;
  502. var offset = option.offset || 0;
  503. var conditions = {
  504. creator: user._id,
  505. redirectTo: null,
  506. $or: [
  507. {status: null},
  508. {status: STATUS_PUBLISHED},
  509. ],
  510. };
  511. if (!user.equals(currentUser._id)) {
  512. conditions.grant = GRANT_PUBLIC;
  513. }
  514. return new Promise(function(resolve, reject) {
  515. Page
  516. .find(conditions)
  517. .sort({createdAt: -1})
  518. .skip(offset)
  519. .limit(limit)
  520. .populate('revision')
  521. .exec()
  522. .then(function(pages) {
  523. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  524. });
  525. });
  526. };
  527. /**
  528. * Bulk get (for internal only)
  529. */
  530. pageSchema.statics.getStreamOfFindAll = function(options) {
  531. var Page = this
  532. , options = options || {}
  533. , publicOnly = options.publicOnly || true
  534. , criteria = {redirectTo: null,}
  535. ;
  536. if (publicOnly) {
  537. criteria.grant = GRANT_PUBLIC;
  538. }
  539. return this.find(criteria)
  540. .populate([
  541. {path: 'creator', model: 'User'},
  542. {path: 'revision', model: 'Revision'},
  543. ])
  544. .sort({updatedAt: -1})
  545. .cursor();
  546. };
  547. /**
  548. * find the page that is match with `path` and its descendants
  549. */
  550. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  551. var Page = this;
  552. // ignore other pages than descendants
  553. path = Page.addSlashOfEnd(path);
  554. // add option to escape the regex strings
  555. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  556. return Page.findListByStartWith(path, userData, combinedOption);
  557. };
  558. /**
  559. * find pages that start with `path`
  560. *
  561. * see the comment of `generateQueryToListByStartWith` function
  562. */
  563. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  564. var Page = this;
  565. var User = crowi.model('User');
  566. if (!option) {
  567. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  568. }
  569. var opt = {
  570. sort: option.sort || 'updatedAt',
  571. desc: option.desc || -1,
  572. offset: option.offset || 0,
  573. limit: option.limit || 50
  574. };
  575. var sortOpt = {};
  576. sortOpt[opt.sort] = opt.desc;
  577. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  578. return new Promise(function(resolve, reject) {
  579. var q = Page.generateQueryToListByStartWith(path, userData, option)
  580. .sort(sortOpt)
  581. .skip(opt.offset)
  582. .limit(opt.limit);
  583. // retrieve revision data
  584. if (isPopulateRevisionBody) {
  585. q = q.populate('revision');
  586. }
  587. else {
  588. q = q.populate('revision', '-body'); // exclude body
  589. }
  590. q.exec()
  591. .then(function(pages) {
  592. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  593. .then(resolve)
  594. .catch(reject);
  595. })
  596. });
  597. };
  598. /**
  599. * generate the query to find the page that is match with `path` and its descendants
  600. */
  601. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  602. var Page = this;
  603. // ignore other pages than descendants
  604. path = Page.addSlashOfEnd(path);
  605. // add option to escape the regex strings
  606. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  607. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  608. };
  609. /**
  610. * generate the query to find pages that start with `path`
  611. *
  612. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  613. * If `path` doesn't have `/` at the end, returns '{path}*'
  614. *
  615. * *option*
  616. * - includeDeletedPage -- if true, search deleted pages (default: false)
  617. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  618. */
  619. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  620. var Page = this;
  621. var pathCondition = [];
  622. var includeDeletedPage = option.includeDeletedPage || false;
  623. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  624. // create forward match pattern
  625. var pattern = (isRegExpEscapedFromPath)
  626. ? `^${escapeStringRegexp(path)}` // escape
  627. : `^${path}`;
  628. var queryReg = new RegExp(pattern);
  629. pathCondition.push({path: queryReg});
  630. // add condition for finding the page completely match with `path`
  631. if (path.match(/\/$/)) {
  632. debug('Page list by ending with /, so find also upper level page');
  633. pathCondition.push({path: path.substr(0, path.length -1)});
  634. }
  635. var q = Page.find({
  636. redirectTo: null,
  637. $or: [
  638. {grant: null},
  639. {grant: GRANT_PUBLIC},
  640. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  641. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  642. {grant: GRANT_OWNER, grantedUsers: userData._id},
  643. ],})
  644. .and({
  645. $or: pathCondition
  646. });
  647. if (!includeDeletedPage) {
  648. q.and({
  649. $or: [
  650. {status: null},
  651. {status: STATUS_PUBLISHED},
  652. ],
  653. });
  654. }
  655. return q;
  656. }
  657. pageSchema.statics.updatePageProperty = function(page, updateData) {
  658. var Page = this;
  659. return new Promise(function(resolve, reject) {
  660. // TODO foreach して save
  661. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  662. if (err) {
  663. return reject(err);
  664. }
  665. return resolve(data);
  666. });
  667. });
  668. };
  669. pageSchema.statics.updateGrant = function (page, grant, userData, grantUserGroupId) {
  670. var Page = this;
  671. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  672. throw new Error('grant userGroupId is not specified');
  673. }
  674. return new Promise(function(resolve, reject) {
  675. page.grant = grant;
  676. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  677. page.grantedUsers = [];
  678. } else {
  679. page.grantedUsers = [];
  680. page.grantedUsers.push(userData._id);
  681. }
  682. page.save(function(err, data) {
  683. debug('Page.updateGrant, saved grantedUsers.', err, data);
  684. if (err) {
  685. return reject(err);
  686. }
  687. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  688. .then(() => {
  689. return resolve(data);
  690. });
  691. });
  692. });
  693. };
  694. pageSchema.statics.updateGrantUserGroup = function (page, grant, grantUserGroupId, userData) {
  695. var UserGroupRelation = crowi.model('UserGroupRelation');
  696. var PageGroupRelation = crowi.model('PageGroupRelation');
  697. // グループの場合
  698. if (grant == GRANT_USER_GROUP) {
  699. debug('grant is usergroup', grantUserGroupId);
  700. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  701. .then((relation) => {
  702. if (relation == null) {
  703. return reject(new Error('no relations were exist for group and user.'));
  704. }
  705. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  706. })
  707. .catch((err) => {
  708. return reject(new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId));
  709. });
  710. }
  711. else {
  712. return PageGroupRelation.removeAllByPage(page);
  713. }
  714. };
  715. // Instance method でいいのでは
  716. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  717. return new Promise(function(resolve, reject) {
  718. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  719. page.grantedUsers = [];
  720. }
  721. page.grantedUsers.push(userData);
  722. page.save(function(err, data) {
  723. if (err) {
  724. return reject(err);
  725. }
  726. return resolve(data);
  727. });
  728. });
  729. };
  730. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  731. var isCreate = false;
  732. if (pageData.revision === undefined) {
  733. debug('pushRevision on Create');
  734. isCreate = true;
  735. }
  736. return new Promise(function(resolve, reject) {
  737. newRevision.save(function(err, newRevision) {
  738. if (err) {
  739. debug('Error on saving revision', err);
  740. return reject(err);
  741. }
  742. debug('Successfully saved new revision', newRevision);
  743. pageData.revision = newRevision;
  744. pageData.lastUpdateUser = user;
  745. pageData.updatedAt = Date.now();
  746. pageData.save(function(err, data) {
  747. if (err) {
  748. // todo: remove new revision?
  749. debug('Error on save page data (after push revision)', err);
  750. return reject(err);
  751. }
  752. resolve(data);
  753. if (!isCreate) {
  754. debug('pushRevision on Update');
  755. }
  756. });
  757. });
  758. });
  759. };
  760. pageSchema.statics.create = function(path, body, user, options) {
  761. var Page = this
  762. , Revision = crowi.model('Revision')
  763. , format = options.format || 'markdown'
  764. , grant = options.grant || GRANT_PUBLIC
  765. , redirectTo = options.redirectTo || null
  766. , grantUserGroupId = options.grantUserGroupId || null;
  767. // force public
  768. if (isPortalPath(path)) {
  769. grant = GRANT_PUBLIC;
  770. }
  771. return new Promise(function(resolve, reject) {
  772. Page.findOne({path: path}, function(err, pageData) {
  773. if (pageData) {
  774. return reject(new Error('Cannot create new page to existed path'));
  775. }
  776. var newPage = new Page();
  777. newPage.path = path;
  778. newPage.creator = user;
  779. newPage.lastUpdateUser = user;
  780. newPage.createdAt = Date.now();
  781. newPage.updatedAt = Date.now();
  782. newPage.redirectTo = redirectTo;
  783. newPage.grant = grant;
  784. newPage.status = STATUS_PUBLISHED;
  785. newPage.grantedUsers = [];
  786. newPage.grantedUsers.push(user);
  787. newPage.save(function (err, newPage) {
  788. if (err) {
  789. return reject(err);
  790. }
  791. if (newPage.grant == Page.GRANT_USER_GROUP && grantUserGroupId != null) {
  792. Page.updateGrantUserGroup(newPage, grant, grantUserGroupId, user)
  793. .catch((err) => {
  794. return reject(err);
  795. });
  796. }
  797. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  798. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  799. resolve(data);
  800. pageEvent.emit('create', data, user);
  801. }).catch(function(err) {
  802. debug('Push Revision Error on create page', err);
  803. return reject(err);
  804. });
  805. });
  806. });
  807. });
  808. };
  809. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  810. var Page = this
  811. , Revision = crowi.model('Revision')
  812. , grant = options.grant || null
  813. , grantUserGroupId = options.grantUserGroupId || null
  814. ;
  815. // update existing page
  816. var newRevision = Revision.prepareRevision(pageData, body, user);
  817. return new Promise(function(resolve, reject) {
  818. Page.pushRevision(pageData, newRevision, user)
  819. .then(function(revision) {
  820. if (grant != pageData.grant) {
  821. return Page.updateGrant(pageData, grant, user, grantUserGroupId).then(function(data) {
  822. debug('Page grant update:', data);
  823. resolve(data);
  824. pageEvent.emit('update', data, user);
  825. });
  826. } else {
  827. resolve(pageData);
  828. pageEvent.emit('update', pageData, user);
  829. }
  830. }).catch(function(err) {
  831. debug('Error on update', err);
  832. debug('Error on update', err.stack);
  833. });
  834. });
  835. };
  836. pageSchema.statics.deletePage = function(pageData, user, options) {
  837. var Page = this
  838. , newPath = Page.getDeletedPageName(pageData.path)
  839. ;
  840. if (Page.isDeletableName(pageData.path)) {
  841. return new Promise(function(resolve, reject) {
  842. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  843. .then(function(data) {
  844. pageData.status = STATUS_DELETED;
  845. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  846. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  847. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  848. debug('Deleted the page, and rename it', pageData.path, newPath);
  849. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  850. }).then(function(pageData) {
  851. resolve(pageData);
  852. }).catch(reject);
  853. });
  854. } else {
  855. return Promise.reject('Page is not deletable.');
  856. }
  857. };
  858. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  859. var Page = this
  860. , path = pageData.path
  861. , options = options || {}
  862. ;
  863. return new Promise(function (resolve, reject) {
  864. Page
  865. .generateQueryToListWithDescendants(path, user, options)
  866. .then(function (pages) {
  867. Promise.all(pages.map(function (page) {
  868. return Page.deletePage(page, user, options);
  869. }))
  870. .then(function (data) {
  871. return resolve(pageData);
  872. });
  873. });
  874. });
  875. };
  876. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  877. var Page = this
  878. , newPath = Page.getRevertDeletedPageName(pageData.path)
  879. ;
  880. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  881. // そのため、そいつは削除してOK
  882. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  883. return new Promise(function(resolve, reject) {
  884. Page.findPageByPath(newPath)
  885. .then(function(originPageData) {
  886. if (originPageData.redirectTo !== pageData.path) {
  887. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  888. }
  889. return Page.completelyDeletePage(originPageData);
  890. }).then(function(done) {
  891. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  892. }).then(function(done) {
  893. pageData.status = STATUS_PUBLISHED;
  894. debug('Revert deleted the page, and rename again it', pageData, newPath);
  895. return Page.rename(pageData, newPath, user, {})
  896. }).then(function(done) {
  897. pageData.path = newPath;
  898. resolve(pageData);
  899. }).catch(reject);
  900. });
  901. };
  902. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  903. var Page = this
  904. , path = pageData.path
  905. , options = options || { includeDeletedPage: true}
  906. ;
  907. return new Promise(function (resolve, reject) {
  908. Page
  909. .generateQueryToListWithDescendants(path, user, options)
  910. .then(function (pages) {
  911. Promise.all(pages.map(function (page) {
  912. return Page.revertDeletedPage(page, user, options);
  913. }))
  914. .then(function (data) {
  915. return resolve(data[0]);
  916. });
  917. });
  918. });
  919. };
  920. /**
  921. * This is danger.
  922. */
  923. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  924. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  925. var Bookmark = crowi.model('Bookmark')
  926. , Attachment = crowi.model('Attachment')
  927. , Comment = crowi.model('Comment')
  928. , Revision = crowi.model('Revision')
  929. , Page = this
  930. , pageId = pageData._id
  931. ;
  932. debug('Completely delete', pageData.path);
  933. return new Promise(function(resolve, reject) {
  934. Bookmark.removeBookmarksByPageId(pageId)
  935. .then(function(done) {
  936. }).then(function(done) {
  937. return Attachment.removeAttachmentsByPageId(pageId);
  938. }).then(function(done) {
  939. return Comment.removeCommentsByPageId(pageId);
  940. }).then(function(done) {
  941. return Revision.removeRevisionsByPath(pageData.path);
  942. }).then(function(done) {
  943. return Page.removePageById(pageId);
  944. }).then(function(done) {
  945. return Page.removeRedirectOriginPageByPath(pageData.path);
  946. }).then(function(done) {
  947. pageEvent.emit('delete', pageData, user); // update as renamed page
  948. resolve(pageData);
  949. }).catch(reject);
  950. });
  951. };
  952. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  953. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  954. var Page = this
  955. , path = pageData.path
  956. , options = options || { includeDeletedPage: true }
  957. ;
  958. return new Promise(function (resolve, reject) {
  959. Page
  960. .generateQueryToListWithDescendants(path, user, options)
  961. .then(function (pages) {
  962. Promise.all(pages.map(function (page) {
  963. return Page.completelyDeletePage(page, user, options);
  964. }))
  965. .then(function (data) {
  966. return resolve(data[0]);
  967. });
  968. });
  969. });
  970. };
  971. pageSchema.statics.removePageById = function(pageId) {
  972. var Page = this;
  973. return new Promise(function(resolve, reject) {
  974. Page.remove({_id: pageId}, function(err, done) {
  975. debug('Remove phisiaclly, the page', pageId, err, done);
  976. if (err) {
  977. return reject(err);
  978. }
  979. resolve(done);
  980. });
  981. });
  982. };
  983. pageSchema.statics.removePageByPath = function(pagePath) {
  984. var Page = this;
  985. return Page.findPageByPath(pagePath)
  986. .then(function(pageData) {
  987. return Page.removePageById(pageData.id);
  988. });
  989. };
  990. /**
  991. * remove the page that is redirecting to specified `pagePath` recursively
  992. * ex: when
  993. * '/page1' redirects to '/page2' and
  994. * '/page2' redirects to '/page3'
  995. * and given '/page3',
  996. * '/page1' and '/page2' will be removed
  997. *
  998. * @param {string} pagePath
  999. */
  1000. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1001. var Page = this;
  1002. return Page.findPageByRedirectTo(pagePath)
  1003. .then((redirectOriginPageData) => {
  1004. // remove
  1005. return Page.removePageById(redirectOriginPageData.id)
  1006. // remove recursive
  1007. .then(() => {
  1008. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  1009. });
  1010. })
  1011. .catch((err) => {
  1012. // do nothing if origin page doesn't exist
  1013. return Promise.resolve();
  1014. })
  1015. };
  1016. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1017. var Page = this
  1018. , Revision = crowi.model('Revision')
  1019. , path = pageData.path
  1020. , createRedirectPage = options.createRedirectPage || 0
  1021. , moveUnderTrees = options.moveUnderTrees || 0;
  1022. return new Promise(function(resolve, reject) {
  1023. // pageData の path を変更
  1024. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  1025. .then(function(data) {
  1026. // reivisions の path を変更
  1027. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  1028. }).then(function(data) {
  1029. pageData.path = newPagePath;
  1030. if (createRedirectPage) {
  1031. var body = 'redirect ' + newPagePath;
  1032. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  1033. } else {
  1034. resolve(data);
  1035. }
  1036. pageEvent.emit('update', pageData, user); // update as renamed page
  1037. });
  1038. });
  1039. };
  1040. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1041. var Page = this
  1042. , path = pageData.path
  1043. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1044. return new Promise(function(resolve, reject) {
  1045. Page
  1046. .generateQueryToListWithDescendants(path, user, options)
  1047. .then(function(pages) {
  1048. Promise.all(pages.map(function(page) {
  1049. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1050. return Page.rename(page, newPagePath, user, options);
  1051. }))
  1052. .then(function() {
  1053. pageData.path = newPagePathPrefix;
  1054. return resolve();
  1055. });
  1056. });
  1057. });
  1058. };
  1059. pageSchema.statics.getHistories = function() {
  1060. // TODO
  1061. return;
  1062. };
  1063. /**
  1064. * return path that added slash to the end for specified path
  1065. */
  1066. pageSchema.statics.addSlashOfEnd = function(path) {
  1067. let returnPath = path;
  1068. if (!path.match(/\/$/)) {
  1069. returnPath += '/';
  1070. }
  1071. return returnPath;
  1072. }
  1073. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1074. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1075. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1076. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1077. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1078. return mongoose.model('Page', pageSchema);
  1079. };