page.js 38 KB

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