2
0

page.js 40 KB

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