page.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. module.exports = function(crowi) {
  2. var debug = require('debug')('growi: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. let pathSlashOmitted = path;
  625. if (path.match(/\/$/)) {
  626. // add condition for finding the page completely match with `path`
  627. pathSlashOmitted = path.substr(0, path.length -1);
  628. pathCondition.push({path: pathSlashOmitted});
  629. }
  630. // create forward match pattern
  631. var pattern = (isRegExpEscapedFromPath)
  632. ? escapeStringRegexp(pathSlashOmitted) // escape
  633. : pathSlashOmitted;
  634. var queryReg = new RegExp('^' + pattern);
  635. pathCondition.push({path: queryReg});
  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. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  673. throw new Error('grant userGroupId is not specified');
  674. }
  675. return new Promise(function(resolve, reject) {
  676. page.grant = grant;
  677. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  678. page.grantedUsers = [];
  679. } else {
  680. page.grantedUsers = [];
  681. page.grantedUsers.push(userData._id);
  682. }
  683. page.save(function(err, data) {
  684. debug('Page.updateGrant, saved grantedUsers.', err, data);
  685. if (err) {
  686. return reject(err);
  687. }
  688. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  689. .then(() => {
  690. return resolve(data);
  691. });
  692. });
  693. });
  694. };
  695. pageSchema.statics.updateGrantUserGroup = function (page, grant, grantUserGroupId, userData) {
  696. var UserGroupRelation = crowi.model('UserGroupRelation');
  697. var PageGroupRelation = crowi.model('PageGroupRelation');
  698. // グループの場合
  699. if (grant == GRANT_USER_GROUP) {
  700. debug('grant is usergroup', grantUserGroupId);
  701. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  702. .then((relation) => {
  703. if (relation == null) {
  704. return reject(new Error('no relations were exist for group and user.'));
  705. }
  706. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  707. })
  708. .catch((err) => {
  709. return reject(new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId));
  710. });
  711. }
  712. else {
  713. return PageGroupRelation.removeAllByPage(page);
  714. }
  715. };
  716. // Instance method でいいのでは
  717. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  718. return new Promise(function(resolve, reject) {
  719. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  720. page.grantedUsers = [];
  721. }
  722. page.grantedUsers.push(userData);
  723. page.save(function(err, data) {
  724. if (err) {
  725. return reject(err);
  726. }
  727. return resolve(data);
  728. });
  729. });
  730. };
  731. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  732. var isCreate = false;
  733. if (pageData.revision === undefined) {
  734. debug('pushRevision on Create');
  735. isCreate = true;
  736. }
  737. return new Promise(function(resolve, reject) {
  738. newRevision.save(function(err, newRevision) {
  739. if (err) {
  740. debug('Error on saving revision', err);
  741. return reject(err);
  742. }
  743. debug('Successfully saved new revision', newRevision);
  744. pageData.revision = newRevision;
  745. pageData.lastUpdateUser = user;
  746. pageData.updatedAt = Date.now();
  747. pageData.save(function(err, data) {
  748. if (err) {
  749. // todo: remove new revision?
  750. debug('Error on save page data (after push revision)', err);
  751. return reject(err);
  752. }
  753. resolve(data);
  754. if (!isCreate) {
  755. debug('pushRevision on Update');
  756. }
  757. });
  758. });
  759. });
  760. };
  761. pageSchema.statics.create = function(path, body, user, options) {
  762. var Page = this
  763. , Revision = crowi.model('Revision')
  764. , format = options.format || 'markdown'
  765. , grant = options.grant || GRANT_PUBLIC
  766. , redirectTo = options.redirectTo || null
  767. , grantUserGroupId = options.grantUserGroupId || null;
  768. // force public
  769. if (isPortalPath(path)) {
  770. grant = GRANT_PUBLIC;
  771. }
  772. return new Promise(function(resolve, reject) {
  773. Page.findOne({path: path}, function(err, pageData) {
  774. if (pageData) {
  775. return reject(new Error('Cannot create new page to existed path'));
  776. }
  777. var newPage = new Page();
  778. newPage.path = path;
  779. newPage.creator = user;
  780. newPage.lastUpdateUser = user;
  781. newPage.createdAt = Date.now();
  782. newPage.updatedAt = Date.now();
  783. newPage.redirectTo = redirectTo;
  784. newPage.grant = grant;
  785. newPage.status = STATUS_PUBLISHED;
  786. newPage.grantedUsers = [];
  787. newPage.grantedUsers.push(user);
  788. newPage.save(function (err, newPage) {
  789. if (err) {
  790. return reject(err);
  791. }
  792. if (newPage.grant == Page.GRANT_USER_GROUP && grantUserGroupId != null) {
  793. Page.updateGrantUserGroup(newPage, grant, grantUserGroupId, user)
  794. .catch((err) => {
  795. return reject(err);
  796. });
  797. }
  798. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  799. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  800. resolve(data);
  801. pageEvent.emit('create', data, user);
  802. }).catch(function(err) {
  803. debug('Push Revision Error on create page', err);
  804. return reject(err);
  805. });
  806. });
  807. });
  808. });
  809. };
  810. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  811. var Page = this
  812. , Revision = crowi.model('Revision')
  813. , grant = options.grant || null
  814. , grantUserGroupId = options.grantUserGroupId || null
  815. ;
  816. // update existing page
  817. var newRevision = Revision.prepareRevision(pageData, body, user);
  818. return new Promise(function(resolve, reject) {
  819. Page.pushRevision(pageData, newRevision, user)
  820. .then(function(revision) {
  821. if (grant != pageData.grant) {
  822. return Page.updateGrant(pageData, grant, user, grantUserGroupId).then(function(data) {
  823. debug('Page grant update:', data);
  824. resolve(data);
  825. pageEvent.emit('update', data, user);
  826. });
  827. } else {
  828. resolve(pageData);
  829. pageEvent.emit('update', pageData, user);
  830. }
  831. }).catch(function(err) {
  832. debug('Error on update', err);
  833. debug('Error on update', err.stack);
  834. });
  835. });
  836. };
  837. pageSchema.statics.deletePage = function(pageData, user, options) {
  838. var Page = this
  839. , newPath = Page.getDeletedPageName(pageData.path)
  840. ;
  841. if (Page.isDeletableName(pageData.path)) {
  842. return new Promise(function(resolve, reject) {
  843. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  844. .then(function(data) {
  845. pageData.status = STATUS_DELETED;
  846. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  847. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  848. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  849. debug('Deleted the page, and rename it', pageData.path, newPath);
  850. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  851. }).then(function(pageData) {
  852. resolve(pageData);
  853. }).catch(reject);
  854. });
  855. } else {
  856. return Promise.reject('Page is not deletable.');
  857. }
  858. };
  859. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  860. var Page = this
  861. , path = pageData.path
  862. , options = options || {}
  863. ;
  864. return new Promise(function (resolve, reject) {
  865. Page
  866. .generateQueryToListWithDescendants(path, user, options)
  867. .then(function (pages) {
  868. Promise.all(pages.map(function (page) {
  869. return Page.deletePage(page, user, options);
  870. }))
  871. .then(function (data) {
  872. return resolve(pageData);
  873. });
  874. });
  875. });
  876. };
  877. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  878. var Page = this
  879. , newPath = Page.getRevertDeletedPageName(pageData.path)
  880. ;
  881. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  882. // そのため、そいつは削除してOK
  883. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  884. return new Promise(function(resolve, reject) {
  885. Page.findPageByPath(newPath)
  886. .then(function(originPageData) {
  887. if (originPageData.redirectTo !== pageData.path) {
  888. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  889. }
  890. return Page.completelyDeletePage(originPageData);
  891. }).then(function(done) {
  892. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  893. }).then(function(done) {
  894. pageData.status = STATUS_PUBLISHED;
  895. debug('Revert deleted the page, and rename again it', pageData, newPath);
  896. return Page.rename(pageData, newPath, user, {})
  897. }).then(function(done) {
  898. pageData.path = newPath;
  899. resolve(pageData);
  900. }).catch(reject);
  901. });
  902. };
  903. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  904. var Page = this
  905. , path = pageData.path
  906. , options = options || { includeDeletedPage: true}
  907. ;
  908. return new Promise(function (resolve, reject) {
  909. Page
  910. .generateQueryToListWithDescendants(path, user, options)
  911. .then(function (pages) {
  912. Promise.all(pages.map(function (page) {
  913. return Page.revertDeletedPage(page, user, options);
  914. }))
  915. .then(function (data) {
  916. return resolve(data[0]);
  917. });
  918. });
  919. });
  920. };
  921. /**
  922. * This is danger.
  923. */
  924. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  925. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  926. var Bookmark = crowi.model('Bookmark')
  927. , Attachment = crowi.model('Attachment')
  928. , Comment = crowi.model('Comment')
  929. , Revision = crowi.model('Revision')
  930. , Page = this
  931. , pageId = pageData._id
  932. ;
  933. debug('Completely delete', pageData.path);
  934. return new Promise(function(resolve, reject) {
  935. Bookmark.removeBookmarksByPageId(pageId)
  936. .then(function(done) {
  937. }).then(function(done) {
  938. return Attachment.removeAttachmentsByPageId(pageId);
  939. }).then(function(done) {
  940. return Comment.removeCommentsByPageId(pageId);
  941. }).then(function(done) {
  942. return Revision.removeRevisionsByPath(pageData.path);
  943. }).then(function(done) {
  944. return Page.removePageById(pageId);
  945. }).then(function(done) {
  946. return Page.removeRedirectOriginPageByPath(pageData.path);
  947. }).then(function(done) {
  948. pageEvent.emit('delete', pageData, user); // update as renamed page
  949. resolve(pageData);
  950. }).catch(reject);
  951. });
  952. };
  953. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  954. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  955. var Page = this
  956. , path = pageData.path
  957. , options = options || { includeDeletedPage: true }
  958. ;
  959. return new Promise(function (resolve, reject) {
  960. Page
  961. .generateQueryToListWithDescendants(path, user, options)
  962. .then(function (pages) {
  963. Promise.all(pages.map(function (page) {
  964. return Page.completelyDeletePage(page, user, options);
  965. }))
  966. .then(function (data) {
  967. return resolve(data[0]);
  968. });
  969. });
  970. });
  971. };
  972. pageSchema.statics.removePageById = function(pageId) {
  973. var Page = this;
  974. return new Promise(function(resolve, reject) {
  975. Page.remove({_id: pageId}, function(err, done) {
  976. debug('Remove phisiaclly, the page', pageId, err, done);
  977. if (err) {
  978. return reject(err);
  979. }
  980. resolve(done);
  981. });
  982. });
  983. };
  984. pageSchema.statics.removePageByPath = function(pagePath) {
  985. var Page = this;
  986. return Page.findPageByPath(pagePath)
  987. .then(function(pageData) {
  988. return Page.removePageById(pageData.id);
  989. });
  990. };
  991. /**
  992. * remove the page that is redirecting to specified `pagePath` recursively
  993. * ex: when
  994. * '/page1' redirects to '/page2' and
  995. * '/page2' redirects to '/page3'
  996. * and given '/page3',
  997. * '/page1' and '/page2' will be removed
  998. *
  999. * @param {string} pagePath
  1000. */
  1001. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1002. var Page = this;
  1003. return Page.findPageByRedirectTo(pagePath)
  1004. .then((redirectOriginPageData) => {
  1005. // remove
  1006. return Page.removePageById(redirectOriginPageData.id)
  1007. // remove recursive
  1008. .then(() => {
  1009. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  1010. });
  1011. })
  1012. .catch((err) => {
  1013. // do nothing if origin page doesn't exist
  1014. return Promise.resolve();
  1015. })
  1016. };
  1017. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1018. var Page = this
  1019. , Revision = crowi.model('Revision')
  1020. , path = pageData.path
  1021. , createRedirectPage = options.createRedirectPage || 0
  1022. , moveUnderTrees = options.moveUnderTrees || 0;
  1023. return new Promise(function(resolve, reject) {
  1024. // pageData の path を変更
  1025. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  1026. .then(function(data) {
  1027. // reivisions の path を変更
  1028. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  1029. }).then(function(data) {
  1030. pageData.path = newPagePath;
  1031. if (createRedirectPage) {
  1032. var body = 'redirect ' + newPagePath;
  1033. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  1034. } else {
  1035. resolve(data);
  1036. }
  1037. pageEvent.emit('update', pageData, user); // update as renamed page
  1038. });
  1039. });
  1040. };
  1041. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1042. var Page = this
  1043. , path = pageData.path
  1044. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1045. return new Promise(function(resolve, reject) {
  1046. Page
  1047. .generateQueryToListWithDescendants(path, user, options)
  1048. .then(function(pages) {
  1049. Promise.all(pages.map(function(page) {
  1050. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1051. return Page.rename(page, newPagePath, user, options);
  1052. }))
  1053. .then(function() {
  1054. pageData.path = newPagePathPrefix;
  1055. return resolve();
  1056. });
  1057. });
  1058. });
  1059. };
  1060. pageSchema.statics.getHistories = function() {
  1061. // TODO
  1062. return;
  1063. };
  1064. /**
  1065. * return path that added slash to the end for specified path
  1066. */
  1067. pageSchema.statics.addSlashOfEnd = function(path) {
  1068. let returnPath = path;
  1069. if (!path.match(/\/$/)) {
  1070. returnPath += '/';
  1071. }
  1072. return returnPath;
  1073. }
  1074. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1075. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1076. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1077. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1078. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1079. return mongoose.model('Page', pageSchema);
  1080. };