page.js 37 KB

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