page.js 36 KB

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