page.js 39 KB

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