page.js 38 KB

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