page.js 38 KB

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