page.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. // check if a given page has a children and decendants tempalte
  452. pageSchema.statics.checkIfTemplatesExist = function(path) {
  453. const Page = this;
  454. const pathList = generatePathsOnTree(path, []);
  455. const regexpList = pathList.map(path => new RegExp(`${path}/_{1,2}template`));
  456. let templateInfo = {
  457. childrenTemplateExists: false,
  458. decendantsTemplateExists: false,
  459. };
  460. return Page
  461. .find({path: {$in: regexpList}})
  462. .then(templates => {
  463. templateInfo.childrenTemplateExists = (assignTemplateByType(templates, path, '_') ? true : false);
  464. templateInfo.decendantsTemplateExists = (assignTemplateByType(templates, path, '__') ? true : false);
  465. return templateInfo;
  466. });
  467. };
  468. /**
  469. * find all templates applicable to the new page
  470. */
  471. pageSchema.statics.findTemplate = function(path) {
  472. const Page = this;
  473. const templatePath = cutOffLastSlash(path);
  474. const pathList = generatePathsOnTree(templatePath, []);
  475. const regexpList = pathList.map(path => new RegExp(`^${path}/_{1,2}template$`));
  476. return Page
  477. .find({path: {$in: regexpList}})
  478. .populate({path: 'revision', model: 'Revision'})
  479. .then(templates => {
  480. return fetchTemplate(templates, templatePath);
  481. });
  482. };
  483. const cutOffLastSlash = path => {
  484. const lastSlash = path.lastIndexOf('/');
  485. return path.substr(0, lastSlash);
  486. };
  487. const generatePathsOnTree = (path, pathList) => {
  488. pathList.push(path);
  489. if (path === '') {
  490. return pathList;
  491. }
  492. const newPath = cutOffLastSlash(path);
  493. return generatePathsOnTree(newPath, pathList);
  494. };
  495. const assignTemplateByType = (templates, path, type) => {
  496. for (let i = 0; i < templates.length; i++) {
  497. if (templates[i].path === `${path}/${type}template`) {
  498. return templates[i];
  499. }
  500. }
  501. };
  502. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  503. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  504. if (decendantsTemplate) {
  505. return decendantsTemplate;
  506. }
  507. if (path === '') {
  508. return;
  509. }
  510. const newPath = cutOffLastSlash(path);
  511. return assignDecendantsTemplate(decendantsTemplates, newPath);
  512. };
  513. const fetchTemplate = (templates, templatePath) => {
  514. let templateBody;
  515. /**
  516. * get children template
  517. * __tempate: applicable only to immediate decendants
  518. */
  519. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  520. /**
  521. * get decendants templates
  522. * _tempate: applicable to all pages under
  523. */
  524. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  525. if (childrenTemplate) {
  526. templateBody = childrenTemplate.revision.body;
  527. }
  528. else if (decendantsTemplate) {
  529. templateBody = decendantsTemplate.revision.body;
  530. }
  531. return templateBody;
  532. };
  533. // find page by path
  534. pageSchema.statics.findPageByPath = function(path) {
  535. if (path == null) {
  536. return null;
  537. }
  538. return this.findOne({path});
  539. };
  540. pageSchema.statics.findListByPageIds = function(ids, options) {
  541. const Page = this;
  542. const User = crowi.model('User');
  543. const limit = options.limit || 50
  544. , offset = options.skip || 0
  545. ;
  546. options = options || {};
  547. return new Promise(function(resolve, reject) {
  548. Page
  549. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  550. //.sort({createdAt: -1}) // TODO optionize
  551. .skip(offset)
  552. .limit(limit)
  553. .populate([
  554. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  555. {path: 'revision', model: 'Revision'},
  556. ])
  557. .exec(function(err, pages) {
  558. if (err) {
  559. return reject(err);
  560. }
  561. Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  562. if (err) {
  563. return reject(err);
  564. }
  565. return resolve(data);
  566. });
  567. });
  568. });
  569. };
  570. pageSchema.statics.findPageByRedirectTo = function(path) {
  571. var Page = this;
  572. return new Promise(function(resolve, reject) {
  573. Page.findOne({redirectTo: path}, function(err, pageData) {
  574. if (err || pageData === null) {
  575. return reject(err);
  576. }
  577. return resolve(pageData);
  578. });
  579. });
  580. };
  581. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  582. var Page = this;
  583. var User = crowi.model('User');
  584. var limit = option.limit || 50;
  585. var offset = option.offset || 0;
  586. var conditions = {
  587. creator: user._id,
  588. redirectTo: null,
  589. $or: [
  590. {status: null},
  591. {status: STATUS_PUBLISHED},
  592. ],
  593. };
  594. if (!user.equals(currentUser._id)) {
  595. conditions.grant = GRANT_PUBLIC;
  596. }
  597. return new Promise(function(resolve, reject) {
  598. Page
  599. .find(conditions)
  600. .sort({createdAt: -1})
  601. .skip(offset)
  602. .limit(limit)
  603. .populate('revision')
  604. .exec()
  605. .then(function(pages) {
  606. return Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  607. });
  608. });
  609. };
  610. /**
  611. * Bulk get (for internal only)
  612. */
  613. pageSchema.statics.getStreamOfFindAll = function(options) {
  614. var Page = this
  615. , options = options || {}
  616. , publicOnly = options.publicOnly || true
  617. , criteria = {redirectTo: null, }
  618. ;
  619. if (publicOnly) {
  620. criteria.grant = GRANT_PUBLIC;
  621. }
  622. return this.find(criteria)
  623. .populate([
  624. {path: 'creator', model: 'User'},
  625. {path: 'revision', model: 'Revision'},
  626. ])
  627. .sort({updatedAt: -1})
  628. .cursor();
  629. };
  630. /**
  631. * find the page that is match with `path` and its descendants
  632. */
  633. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  634. var Page = this;
  635. // ignore other pages than descendants
  636. path = Page.addSlashOfEnd(path);
  637. // add option to escape the regex strings
  638. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  639. return Page.findListByStartWith(path, userData, combinedOption);
  640. };
  641. /**
  642. * find pages that start with `path`
  643. *
  644. * see the comment of `generateQueryToListByStartWith` function
  645. */
  646. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  647. var Page = this;
  648. var User = crowi.model('User');
  649. if (!option) {
  650. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  651. }
  652. var opt = {
  653. sort: option.sort || 'updatedAt',
  654. desc: option.desc || -1,
  655. offset: option.offset || 0,
  656. limit: option.limit || 50
  657. };
  658. var sortOpt = {};
  659. sortOpt[opt.sort] = opt.desc;
  660. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  661. return new Promise(function(resolve, reject) {
  662. var q = Page.generateQueryToListByStartWith(path, userData, option)
  663. .sort(sortOpt)
  664. .skip(opt.offset)
  665. .limit(opt.limit);
  666. // retrieve revision data
  667. if (isPopulateRevisionBody) {
  668. q = q.populate('revision');
  669. }
  670. else {
  671. q = q.populate('revision', '-body'); // exclude body
  672. }
  673. q.exec()
  674. .then(function(pages) {
  675. Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS})
  676. .then(resolve)
  677. .catch(reject);
  678. });
  679. });
  680. };
  681. /**
  682. * generate the query to find the page that is match with `path` and its descendants
  683. */
  684. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  685. var Page = this;
  686. // ignore other pages than descendants
  687. path = Page.addSlashOfEnd(path);
  688. // add option to escape the regex strings
  689. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  690. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  691. };
  692. /**
  693. * generate the query to find pages that start with `path`
  694. *
  695. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  696. * -> returns '{path}/*' and '{path}' self.
  697. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  698. * -> returns '{path}*'
  699. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  700. * -> returns '{path}*'
  701. *
  702. * *option*
  703. * - includeDeletedPage -- if true, search deleted pages (default: false)
  704. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  705. */
  706. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  707. var Page = this;
  708. var pathCondition = [];
  709. var includeDeletedPage = option.includeDeletedPage || false;
  710. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  711. /*
  712. * 1. add condition for finding the page completely match with `path` w/o last slash
  713. */
  714. let pathSlashOmitted = path;
  715. if (path.match(/\/$/)) {
  716. pathSlashOmitted = path.substr(0, path.length -1);
  717. pathCondition.push({path: pathSlashOmitted});
  718. }
  719. /*
  720. * 2. add decendants
  721. */
  722. var pattern = (isRegExpEscapedFromPath)
  723. ? escapeStringRegexp(path) // escape
  724. : pathSlashOmitted;
  725. var queryReg = new RegExp('^' + pattern);
  726. pathCondition.push({path: queryReg});
  727. var q = Page.find({
  728. redirectTo: null,
  729. $or: [
  730. {grant: null},
  731. {grant: GRANT_PUBLIC},
  732. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  733. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  734. {grant: GRANT_OWNER, grantedUsers: userData._id},
  735. {grant: GRANT_USER_GROUP},
  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. return new Promise(function(resolve, reject) {
  765. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  766. reject('grant userGroupId is not specified');
  767. }
  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 new Error('no relations were exist for group and user.');
  798. }
  799. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  800. })
  801. .catch((err) => {
  802. return 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. let savedPage = undefined;
  866. return Page.findOne({path: path})
  867. .then(pageData => {
  868. if (pageData) {
  869. throw new Error('Cannot create new page to existed path');
  870. }
  871. var newPage = new Page();
  872. newPage.path = path;
  873. newPage.creator = user;
  874. newPage.lastUpdateUser = user;
  875. newPage.createdAt = Date.now();
  876. newPage.updatedAt = Date.now();
  877. newPage.redirectTo = redirectTo;
  878. newPage.grant = grant;
  879. newPage.status = STATUS_PUBLISHED;
  880. newPage.grantedUsers = [];
  881. newPage.grantedUsers.push(user);
  882. return newPage.save();
  883. })
  884. .then((newPage) => {
  885. savedPage = newPage;
  886. })
  887. .then(() => {
  888. const newRevision = Revision.prepareRevision(savedPage, body, user, {format: format});
  889. return Page.pushRevision(savedPage, newRevision, user);
  890. })
  891. .then(() => {
  892. return Page.updateGrantUserGroup(savedPage, grant, grantUserGroupId, user);
  893. })
  894. .then(() => {
  895. pageEvent.emit('create', savedPage, user);
  896. return savedPage;
  897. });
  898. };
  899. pageSchema.statics.updatePage = async function(pageData, body, user, options) {
  900. var Page = this
  901. , Revision = crowi.model('Revision')
  902. , grant = options.grant || null
  903. , grantUserGroupId = options.grantUserGroupId || null
  904. ;
  905. // update existing page
  906. var newRevision = await Revision.prepareRevision(pageData, body, user);
  907. const revision = await Page.pushRevision(pageData, newRevision, user);
  908. const savedPage = await Page.findPageByPath(revision.path).populate('revision');
  909. if (grant != null) {
  910. const grantData = await Page.updateGrant(savedPage, grant, user, grantUserGroupId);
  911. debug('Page grant update:', grantData);
  912. }
  913. pageEvent.emit('update', savedPage, user);
  914. return savedPage;
  915. };
  916. pageSchema.statics.deletePage = function(pageData, user, options) {
  917. var Page = this
  918. , newPath = Page.getDeletedPageName(pageData.path)
  919. ;
  920. if (Page.isDeletableName(pageData.path)) {
  921. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  922. .then((updatedPageData) => {
  923. return Page.updatePageProperty(updatedPageData, {status: STATUS_DELETED, lastUpdateUser: user});
  924. })
  925. .then(() => {
  926. return pageData;
  927. });
  928. }
  929. else {
  930. return Promise.reject('Page is not deletable.');
  931. }
  932. };
  933. pageSchema.statics.deletePageRecursively = function(pageData, user, options) {
  934. var Page = this
  935. , path = pageData.path
  936. , options = options || {}
  937. ;
  938. return Page.generateQueryToListWithDescendants(path, user, options)
  939. .then(function(pages) {
  940. return Promise.all(pages.map(function(page) {
  941. return Page.deletePage(page, user, options);
  942. }));
  943. })
  944. .then(function(data) {
  945. return pageData;
  946. });
  947. };
  948. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  949. var Page = this
  950. , newPath = Page.getRevertDeletedPageName(pageData.path)
  951. ;
  952. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  953. // そのため、そいつは削除してOK
  954. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  955. return new Promise(function(resolve, reject) {
  956. Page.findPageByPath(newPath)
  957. .then(function(originPageData) {
  958. if (originPageData.redirectTo !== pageData.path) {
  959. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  960. }
  961. return Page.completelyDeletePage(originPageData);
  962. }).then(function(done) {
  963. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user});
  964. }).then(function(done) {
  965. pageData.status = STATUS_PUBLISHED;
  966. debug('Revert deleted the page, and rename again it', pageData, newPath);
  967. return Page.rename(pageData, newPath, user, {});
  968. }).then(function(done) {
  969. pageData.path = newPath;
  970. resolve(pageData);
  971. }).catch(reject);
  972. });
  973. };
  974. pageSchema.statics.revertDeletedPageRecursively = function(pageData, user, options) {
  975. var Page = this
  976. , path = pageData.path
  977. , options = options || { includeDeletedPage: true}
  978. ;
  979. return new Promise(function(resolve, reject) {
  980. Page
  981. .generateQueryToListWithDescendants(path, user, options)
  982. .exec()
  983. .then(function(pages) {
  984. Promise.all(pages.map(function(page) {
  985. return Page.revertDeletedPage(page, user, options);
  986. }))
  987. .then(function(data) {
  988. return resolve(data[0]);
  989. });
  990. });
  991. });
  992. };
  993. /**
  994. * This is danger.
  995. */
  996. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  997. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  998. var Bookmark = crowi.model('Bookmark')
  999. , Attachment = crowi.model('Attachment')
  1000. , Comment = crowi.model('Comment')
  1001. , Revision = crowi.model('Revision')
  1002. , PageGroupRelation = crowi.model('PageGroupRelation')
  1003. , Page = this
  1004. , pageId = pageData._id
  1005. ;
  1006. debug('Completely delete', pageData.path);
  1007. return new Promise(function(resolve, reject) {
  1008. Bookmark.removeBookmarksByPageId(pageId)
  1009. .then(function(done) {
  1010. }).then(function(done) {
  1011. return Attachment.removeAttachmentsByPageId(pageId);
  1012. }).then(function(done) {
  1013. return Comment.removeCommentsByPageId(pageId);
  1014. }).then(function(done) {
  1015. return Revision.removeRevisionsByPath(pageData.path);
  1016. }).then(function(done) {
  1017. return Page.removePageById(pageId);
  1018. }).then(function(done) {
  1019. return Page.removeRedirectOriginPageByPath(pageData.path);
  1020. }).then(function(done) {
  1021. return PageGroupRelation.removeAllByPage(pageData);
  1022. }).then(function(done) {
  1023. pageEvent.emit('delete', pageData, user); // update as renamed page
  1024. resolve(pageData);
  1025. }).catch(reject);
  1026. });
  1027. };
  1028. pageSchema.statics.completelyDeletePageRecursively = function(pageData, user, options) {
  1029. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1030. var Page = this
  1031. , path = pageData.path
  1032. , options = options || { includeDeletedPage: true }
  1033. ;
  1034. return new Promise(function(resolve, reject) {
  1035. Page
  1036. .generateQueryToListWithDescendants(path, user, options)
  1037. .then(function(pages) {
  1038. Promise.all(pages.map(function(page) {
  1039. return Page.completelyDeletePage(page, user, options);
  1040. }))
  1041. .then(function(data) {
  1042. return resolve(data[0]);
  1043. });
  1044. });
  1045. });
  1046. };
  1047. pageSchema.statics.removePageById = function(pageId) {
  1048. var Page = this;
  1049. return new Promise(function(resolve, reject) {
  1050. Page.remove({_id: pageId}, function(err, done) {
  1051. debug('Remove phisiaclly, the page', pageId, err, done);
  1052. if (err) {
  1053. return reject(err);
  1054. }
  1055. resolve(done);
  1056. });
  1057. });
  1058. };
  1059. pageSchema.statics.removePageByPath = function(pagePath) {
  1060. var Page = this;
  1061. return Page.findPageByPath(pagePath)
  1062. .then(function(pageData) {
  1063. return Page.removePageById(pageData.id);
  1064. });
  1065. };
  1066. /**
  1067. * remove the page that is redirecting to specified `pagePath` recursively
  1068. * ex: when
  1069. * '/page1' redirects to '/page2' and
  1070. * '/page2' redirects to '/page3'
  1071. * and given '/page3',
  1072. * '/page1' and '/page2' will be removed
  1073. *
  1074. * @param {string} pagePath
  1075. */
  1076. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1077. var Page = this;
  1078. return Page.findPageByRedirectTo(pagePath)
  1079. .then((redirectOriginPageData) => {
  1080. // remove
  1081. return Page.removePageById(redirectOriginPageData.id)
  1082. // remove recursive
  1083. .then(() => {
  1084. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path);
  1085. });
  1086. })
  1087. .catch((err) => {
  1088. // do nothing if origin page doesn't exist
  1089. return Promise.resolve();
  1090. });
  1091. };
  1092. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1093. var Page = this
  1094. , Revision = crowi.model('Revision')
  1095. , path = pageData.path
  1096. , createRedirectPage = options.createRedirectPage || 0
  1097. , moveUnderTrees = options.moveUnderTrees || 0;
  1098. return Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user}) // pageData の path を変更
  1099. .then((data) => {
  1100. // reivisions の path を変更
  1101. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  1102. })
  1103. .then(function(data) {
  1104. pageData.path = newPagePath;
  1105. if (createRedirectPage) {
  1106. var body = 'redirect ' + newPagePath;
  1107. Page.create(path, body, user, {redirectTo: newPagePath});
  1108. }
  1109. pageEvent.emit('update', pageData, user); // update as renamed page
  1110. return pageData;
  1111. });
  1112. };
  1113. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1114. var Page = this
  1115. , path = pageData.path
  1116. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1117. return Page.generateQueryToListWithDescendants(path, user, options)
  1118. .then(function(pages) {
  1119. return Promise.all(pages.map(function(page) {
  1120. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1121. return Page.rename(page, newPagePath, user, options);
  1122. }));
  1123. })
  1124. .then(function() {
  1125. pageData.path = newPagePathPrefix;
  1126. return pageData;
  1127. });
  1128. };
  1129. pageSchema.statics.getHistories = function() {
  1130. // TODO
  1131. return;
  1132. };
  1133. /**
  1134. * return path that added slash to the end for specified path
  1135. */
  1136. pageSchema.statics.addSlashOfEnd = function(path) {
  1137. let returnPath = path;
  1138. if (!path.match(/\/$/)) {
  1139. returnPath += '/';
  1140. }
  1141. return returnPath;
  1142. };
  1143. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1144. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1145. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1146. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1147. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1148. return mongoose.model('Page', pageSchema);
  1149. };