page.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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. ;
  30. let pageSchema;
  31. let pageEvent;
  32. // init event
  33. if (crowi != null) {
  34. pageEvent = crowi.event('page');
  35. pageEvent.on('create', pageEvent.onCreate);
  36. pageEvent.on('update', pageEvent.onUpdate);
  37. }
  38. function isPortalPath(path) {
  39. if (path.match(/.*\/$/)) {
  40. return true;
  41. }
  42. return false;
  43. }
  44. function validateCrowi() {
  45. if (crowi == null) {
  46. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  47. }
  48. }
  49. pageSchema = new mongoose.Schema({
  50. path: { type: String, required: true, index: true, unique: true },
  51. revision: { type: ObjectId, ref: 'Revision' },
  52. redirectTo: { type: String, index: true },
  53. status: { type: String, default: STATUS_PUBLISHED, index: true },
  54. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  55. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  56. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  57. creator: { type: ObjectId, ref: 'User', index: true },
  58. lastUpdateUser: { type: ObjectId, ref: 'User', index: true },
  59. liker: [{ type: ObjectId, ref: 'User', index: true }],
  60. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  61. commentCount: { type: Number, default: 0 },
  62. extended: {
  63. type: String,
  64. default: '{}',
  65. get: function(data) {
  66. try {
  67. return JSON.parse(data);
  68. }
  69. catch (e) {
  70. return data;
  71. }
  72. },
  73. set: function(data) {
  74. return JSON.stringify(data);
  75. }
  76. },
  77. pageIdOnHackmd: String,
  78. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  79. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  80. createdAt: { type: Date, default: Date.now },
  81. updatedAt: Date
  82. }, {
  83. toJSON: {getters: true},
  84. toObject: {getters: true}
  85. });
  86. pageSchema.methods.isWIP = function() {
  87. return this.status === STATUS_WIP;
  88. };
  89. pageSchema.methods.isPublished = function() {
  90. // null: this is for B.C.
  91. return this.status === null || this.status === STATUS_PUBLISHED;
  92. };
  93. pageSchema.methods.isDeleted = function() {
  94. return this.status === STATUS_DELETED;
  95. };
  96. pageSchema.methods.isDeprecated = function() {
  97. return this.status === STATUS_DEPRECATED;
  98. };
  99. pageSchema.methods.isPublic = function() {
  100. if (!this.grant || this.grant == GRANT_PUBLIC) {
  101. return true;
  102. }
  103. return false;
  104. };
  105. pageSchema.methods.isPortal = function() {
  106. return isPortalPath(this.path);
  107. };
  108. pageSchema.methods.isTemplate = function() {
  109. return templateChecker(this.path);
  110. };
  111. pageSchema.methods.isGrantedFor = function(userData) {
  112. if (this.isPublic()) {
  113. return true;
  114. }
  115. if (userData != null && this.grantedUsers.indexOf(userData._id) >= 0) {
  116. return true;
  117. }
  118. return false;
  119. };
  120. pageSchema.methods.isLatestRevision = function() {
  121. // populate されていなくて判断できない
  122. if (!this.latestRevision || !this.revision) {
  123. return true;
  124. }
  125. return (this.latestRevision == this.revision._id.toString());
  126. };
  127. pageSchema.methods.isUpdatable = function(previousRevision) {
  128. var revision = this.latestRevision || this.revision;
  129. if (revision != previousRevision) {
  130. return false;
  131. }
  132. return true;
  133. };
  134. pageSchema.methods.isLiked = function(userData) {
  135. return this.liker.some(function(likedUser) {
  136. return likedUser == userData._id.toString();
  137. });
  138. };
  139. pageSchema.methods.like = function(userData) {
  140. var self = this,
  141. Page = self;
  142. return new Promise(function(resolve, reject) {
  143. var added = self.liker.addToSet(userData._id);
  144. if (added.length > 0) {
  145. self.save(function(err, data) {
  146. if (err) {
  147. return reject(err);
  148. }
  149. debug('liker updated!', added);
  150. return resolve(data);
  151. });
  152. }
  153. else {
  154. debug('liker not updated');
  155. return reject(self);
  156. }
  157. });
  158. };
  159. pageSchema.methods.unlike = function(userData, callback) {
  160. var self = this,
  161. Page = self;
  162. return new Promise(function(resolve, reject) {
  163. var beforeCount = self.liker.length;
  164. self.liker.pull(userData._id);
  165. if (self.liker.length != beforeCount) {
  166. self.save(function(err, data) {
  167. if (err) {
  168. return reject(err);
  169. }
  170. return resolve(data);
  171. });
  172. }
  173. else {
  174. debug('liker not updated');
  175. return reject(self);
  176. }
  177. });
  178. };
  179. pageSchema.methods.isSeenUser = function(userData) {
  180. var self = this,
  181. Page = self;
  182. return this.seenUsers.some(function(seenUser) {
  183. return seenUser.equals(userData._id);
  184. });
  185. };
  186. pageSchema.methods.seen = function(userData) {
  187. var self = this,
  188. Page = self;
  189. if (this.isSeenUser(userData)) {
  190. debug('seenUsers not updated');
  191. return Promise.resolve(this);
  192. }
  193. return new Promise(function(resolve, reject) {
  194. if (!userData || !userData._id) {
  195. reject(new Error('User data is not valid'));
  196. }
  197. var added = self.seenUsers.addToSet(userData);
  198. self.save(function(err, data) {
  199. if (err) {
  200. return reject(err);
  201. }
  202. debug('seenUsers updated!', added);
  203. return resolve(self);
  204. });
  205. });
  206. };
  207. pageSchema.methods.getSlackChannel = function() {
  208. const extended = this.get('extended');
  209. if (!extended) {
  210. return '';
  211. }
  212. return extended.slack || '';
  213. };
  214. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  215. const extended = this.extended;
  216. extended.slack = slackChannel;
  217. return this.updateExtended(extended);
  218. };
  219. pageSchema.methods.updateExtended = function(extended) {
  220. const page = this;
  221. page.extended = extended;
  222. return new Promise(function(resolve, reject) {
  223. return page.save(function(err, doc) {
  224. if (err) {
  225. return reject(err);
  226. }
  227. return resolve(doc);
  228. });
  229. });
  230. };
  231. pageSchema.statics.populatePageData = function(pageData, revisionId) {
  232. validateCrowi();
  233. const Page = crowi.model('Page');
  234. const User = crowi.model('User');
  235. pageData.latestRevision = pageData.revision;
  236. if (revisionId) {
  237. pageData.revision = revisionId;
  238. }
  239. pageData.likerCount = pageData.liker.length || 0;
  240. pageData.seenUsersCount = pageData.seenUsers.length || 0;
  241. return new Promise(function(resolve, reject) {
  242. pageData.populate([
  243. {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS},
  244. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  245. {path: 'revision', model: 'Revision'},
  246. //{path: 'liker', options: { limit: 11 }},
  247. //{path: 'seenUsers', options: { limit: 11 }},
  248. ], function(err, pageData) {
  249. Page.populate(pageData, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  250. if (err) {
  251. return reject(err);
  252. }
  253. return resolve(data);
  254. });
  255. });
  256. });
  257. };
  258. pageSchema.statics.populatePageListToAnyObjects = function(pageIdObjectArray) {
  259. var Page = this;
  260. var pageIdMappings = {};
  261. var pageIds = pageIdObjectArray.map(function(page, idx) {
  262. if (!page._id) {
  263. throw new Error('Pass the arg of populatePageListToAnyObjects() must have _id on each element.');
  264. }
  265. pageIdMappings[String(page._id)] = idx;
  266. return page._id;
  267. });
  268. return new Promise(function(resolve, reject) {
  269. Page.findListByPageIds(pageIds, {limit: 100}) // limit => if the pagIds is greater than 100, ignore
  270. .then(function(pages) {
  271. pages.forEach(function(page) {
  272. Object.assign(pageIdObjectArray[pageIdMappings[String(page._id)]], page._doc);
  273. });
  274. resolve(pageIdObjectArray);
  275. });
  276. });
  277. };
  278. pageSchema.statics.updateCommentCount = function(pageId) {
  279. validateCrowi();
  280. const self = this;
  281. const 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 = async function(id) {
  388. const page = await this.findOne({_id: id});
  389. if (page == null) {
  390. throw new Error('Page not found');
  391. }
  392. return this.populatePageData(page, null);
  393. };
  394. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  395. validateCrowi();
  396. const Page = this;
  397. const PageGroupRelation = crowi.model('PageGroupRelation');
  398. let pageData = null;
  399. return new Promise(function(resolve, reject) {
  400. Page.findPageById(id)
  401. .then(function(result) {
  402. pageData = result;
  403. if (userData && !pageData.isGrantedFor(userData)) {
  404. return PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData);
  405. }
  406. else {
  407. return true;
  408. }
  409. }).then((checkResult) => {
  410. console.log(checkResult);
  411. if (checkResult) {
  412. return resolve(pageData);
  413. }
  414. else {
  415. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  416. }
  417. }).catch(function(err) {
  418. return reject(err);
  419. });
  420. });
  421. };
  422. // find page and check if granted user
  423. pageSchema.statics.findPage = async function(path, userData, revisionId, ignoreNotFound) {
  424. validateCrowi();
  425. const PageGroupRelation = crowi.model('PageGroupRelation');
  426. const pageData = await this.findOne({path: path});
  427. if (pageData == null) {
  428. if (ignoreNotFound) {
  429. return null;
  430. }
  431. const pageNotFoundError = new Error('Page Not Found');
  432. pageNotFoundError.name = 'Crowi:Page:NotFound';
  433. throw new Error(pageNotFoundError);
  434. }
  435. if (!pageData.isGrantedFor(userData)) {
  436. const isRelationExists = await PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData);
  437. if (isRelationExists) {
  438. return await this.populatePageData(pageData, revisionId || null);
  439. }
  440. else {
  441. throw new UserHasNoGrantException('Page is not granted for the user', userData);
  442. }
  443. }
  444. else {
  445. return await this.populatePageData(pageData, revisionId || null);
  446. }
  447. };
  448. /**
  449. * find all templates applicable to the new page
  450. */
  451. pageSchema.statics.findTemplate = function(path) {
  452. const Page = this;
  453. const templatePath = cutOffLastSlash(path);
  454. const pathList = generatePathsOnTree(templatePath, []);
  455. const regexpList = pathList.map(path => new RegExp(`^${escapeStringRegexp(path)}/_{1,2}template$`));
  456. return Page
  457. .find({path: {$in: regexpList}})
  458. .populate({path: 'revision', model: 'Revision'})
  459. .then(templates => {
  460. return fetchTemplate(templates, templatePath);
  461. });
  462. };
  463. const cutOffLastSlash = path => {
  464. const lastSlash = path.lastIndexOf('/');
  465. return path.substr(0, lastSlash);
  466. };
  467. const generatePathsOnTree = (path, pathList) => {
  468. pathList.push(path);
  469. if (path === '') {
  470. return pathList;
  471. }
  472. const newPath = cutOffLastSlash(path);
  473. return generatePathsOnTree(newPath, pathList);
  474. };
  475. const assignTemplateByType = (templates, path, type) => {
  476. for (let i = 0; i < templates.length; i++) {
  477. if (templates[i].path === `${path}/${type}template`) {
  478. return templates[i];
  479. }
  480. }
  481. };
  482. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  483. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  484. if (decendantsTemplate) {
  485. return decendantsTemplate;
  486. }
  487. if (path === '') {
  488. return;
  489. }
  490. const newPath = cutOffLastSlash(path);
  491. return assignDecendantsTemplate(decendantsTemplates, newPath);
  492. };
  493. const fetchTemplate = (templates, templatePath) => {
  494. let templateBody;
  495. /**
  496. * get children template
  497. * __tempate: applicable only to immediate decendants
  498. */
  499. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  500. /**
  501. * get decendants templates
  502. * _tempate: applicable to all pages under
  503. */
  504. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  505. if (childrenTemplate) {
  506. templateBody = childrenTemplate.revision.body;
  507. }
  508. else if (decendantsTemplate) {
  509. templateBody = decendantsTemplate.revision.body;
  510. }
  511. return templateBody;
  512. };
  513. // find page by path
  514. pageSchema.statics.findPageByPath = function(path) {
  515. if (path == null) {
  516. return null;
  517. }
  518. return this.findOne({path});
  519. };
  520. pageSchema.statics.findListByPageIds = function(ids, options) {
  521. validateCrowi();
  522. const Page = this;
  523. const User = crowi.model('User');
  524. const limit = options.limit || 50
  525. , offset = options.skip || 0
  526. ;
  527. options = options || {};
  528. return new Promise(function(resolve, reject) {
  529. Page
  530. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  531. //.sort({createdAt: -1}) // TODO optionize
  532. .skip(offset)
  533. .limit(limit)
  534. .populate([
  535. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  536. {path: 'revision', model: 'Revision'},
  537. ])
  538. .exec(function(err, pages) {
  539. if (err) {
  540. return reject(err);
  541. }
  542. Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  543. if (err) {
  544. return reject(err);
  545. }
  546. return resolve(data);
  547. });
  548. });
  549. });
  550. };
  551. pageSchema.statics.findPageByRedirectTo = function(path) {
  552. var Page = this;
  553. return new Promise(function(resolve, reject) {
  554. Page.findOne({redirectTo: path}, function(err, pageData) {
  555. if (err || pageData === null) {
  556. return reject(err);
  557. }
  558. return resolve(pageData);
  559. });
  560. });
  561. };
  562. pageSchema.statics.findListByCreator = async function(user, option, currentUser) {
  563. validateCrowi();
  564. let Page = this;
  565. let User = crowi.model('User');
  566. let limit = option.limit || 50;
  567. let offset = option.offset || 0;
  568. let conditions = setPageListConditions(user);
  569. let pages = await Page.find(conditions).sort({createdAt: -1}).skip(offset).limit(limit).populate('revision').exec();
  570. let PagesList = await Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS});
  571. let totalCount = await Page.countListByCreator(user);
  572. let PagesArray = [
  573. {totalCount: totalCount}
  574. ];
  575. PagesArray.push(PagesList);
  576. return PagesArray;
  577. };
  578. function setPageListConditions(user) {
  579. const conditions = {
  580. creator: user._id,
  581. redirectTo: null,
  582. $and: [
  583. {$or: [
  584. {status: null},
  585. {status: STATUS_PUBLISHED},
  586. ]},
  587. {$or: [
  588. {grant: GRANT_PUBLIC},
  589. {grant: GRANT_USER_GROUP},
  590. ]}],
  591. };
  592. return conditions;
  593. }
  594. pageSchema.statics.countListByCreator = function(user) {
  595. let Page = this;
  596. let conditions = setPageListConditions(user);
  597. return Page.find(conditions).count();
  598. };
  599. /**
  600. * Bulk get (for internal only)
  601. */
  602. pageSchema.statics.getStreamOfFindAll = function(options) {
  603. var Page = this
  604. , options = options || {}
  605. , publicOnly = options.publicOnly || true
  606. , criteria = {redirectTo: null, }
  607. ;
  608. if (publicOnly) {
  609. criteria.grant = GRANT_PUBLIC;
  610. }
  611. return this.find(criteria)
  612. .populate([
  613. {path: 'creator', model: 'User'},
  614. {path: 'revision', model: 'Revision'},
  615. ])
  616. .sort({updatedAt: -1})
  617. .cursor();
  618. };
  619. /**
  620. * find the page that is match with `path` and its descendants
  621. */
  622. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  623. var Page = this;
  624. // ignore other pages than descendants
  625. path = Page.addSlashOfEnd(path);
  626. // add option to escape the regex strings
  627. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  628. return Page.findListByStartWith(path, userData, combinedOption);
  629. };
  630. /**
  631. * find pages that start with `path`
  632. *
  633. * see the comment of `generateQueryToListByStartWith` function
  634. */
  635. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  636. validateCrowi();
  637. const Page = this;
  638. const User = crowi.model('User');
  639. if (!option) {
  640. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  641. }
  642. const opt = {
  643. sort: option.sort || 'updatedAt',
  644. desc: option.desc || -1,
  645. offset: option.offset || 0,
  646. limit: option.limit || 50
  647. };
  648. const sortOpt = {};
  649. sortOpt[opt.sort] = opt.desc;
  650. const isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  651. return new Promise(function(resolve, reject) {
  652. let q = Page.generateQueryToListByStartWith(path, userData, option)
  653. .sort(sortOpt)
  654. .skip(opt.offset)
  655. .limit(opt.limit);
  656. // retrieve revision data
  657. if (isPopulateRevisionBody) {
  658. q = q.populate('revision');
  659. }
  660. else {
  661. q = q.populate('revision', '-body'); // exclude body
  662. }
  663. q.exec()
  664. .then(function(pages) {
  665. Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS})
  666. .then(resolve)
  667. .catch(reject);
  668. });
  669. });
  670. };
  671. /**
  672. * generate the query to find the page that is match with `path` and its descendants
  673. */
  674. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  675. var Page = this;
  676. // ignore other pages than descendants
  677. path = Page.addSlashOfEnd(path);
  678. // add option to escape the regex strings
  679. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  680. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  681. };
  682. /**
  683. * generate the query to find pages that start with `path`
  684. *
  685. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  686. * -> returns '{path}/*' and '{path}' self.
  687. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  688. * -> returns '{path}*'
  689. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  690. * -> returns '{path}*'
  691. *
  692. * *option*
  693. * - includeDeletedPage -- if true, search deleted pages (default: false)
  694. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  695. */
  696. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  697. var Page = this;
  698. var pathCondition = [];
  699. var includeDeletedPage = option.includeDeletedPage || false;
  700. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  701. /*
  702. * 1. add condition for finding the page completely match with `path` w/o last slash
  703. */
  704. let pathSlashOmitted = path;
  705. if (path.match(/\/$/)) {
  706. pathSlashOmitted = path.substr(0, path.length -1);
  707. pathCondition.push({path: pathSlashOmitted});
  708. }
  709. /*
  710. * 2. add decendants
  711. */
  712. var pattern = (isRegExpEscapedFromPath)
  713. ? escapeStringRegexp(path) // escape
  714. : pathSlashOmitted;
  715. var queryReg = new RegExp('^' + pattern);
  716. pathCondition.push({path: queryReg});
  717. var q = Page.find({
  718. redirectTo: null,
  719. $or: [
  720. {grant: null},
  721. {grant: GRANT_PUBLIC},
  722. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  723. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  724. {grant: GRANT_OWNER, grantedUsers: userData._id},
  725. {grant: GRANT_USER_GROUP},
  726. ], })
  727. .and({
  728. $or: pathCondition
  729. });
  730. if (!includeDeletedPage) {
  731. q.and({
  732. $or: [
  733. {status: null},
  734. {status: STATUS_PUBLISHED},
  735. ],
  736. });
  737. }
  738. return q;
  739. };
  740. pageSchema.statics.updatePageProperty = function(page, updateData) {
  741. var Page = this;
  742. return new Promise(function(resolve, reject) {
  743. // TODO foreach して save
  744. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  745. if (err) {
  746. return reject(err);
  747. }
  748. return resolve(data);
  749. });
  750. });
  751. };
  752. pageSchema.statics.updateGrant = function(page, grant, userData, grantUserGroupId) {
  753. var Page = this;
  754. return new Promise(function(resolve, reject) {
  755. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  756. reject('grant userGroupId is not specified');
  757. }
  758. page.grant = grant;
  759. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  760. page.grantedUsers = [];
  761. }
  762. else {
  763. page.grantedUsers = [];
  764. page.grantedUsers.push(userData._id);
  765. }
  766. page.save(function(err, data) {
  767. debug('Page.updateGrant, saved grantedUsers.', err, data);
  768. if (err) {
  769. return reject(err);
  770. }
  771. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  772. .then(() => {
  773. return resolve(data);
  774. });
  775. });
  776. });
  777. };
  778. pageSchema.statics.updateGrantUserGroup = function(page, grant, grantUserGroupId, userData) {
  779. validateCrowi();
  780. const UserGroupRelation = crowi.model('UserGroupRelation');
  781. const PageGroupRelation = crowi.model('PageGroupRelation');
  782. // グループの場合
  783. if (grant == GRANT_USER_GROUP) {
  784. debug('grant is usergroup', grantUserGroupId);
  785. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  786. .then((relation) => {
  787. if (relation == null) {
  788. return new Error('no relations were exist for group and user.');
  789. }
  790. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  791. })
  792. .catch((err) => {
  793. return new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId);
  794. });
  795. }
  796. else {
  797. return PageGroupRelation.removeAllByPage(page);
  798. }
  799. };
  800. // Instance method でいいのでは
  801. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  802. return new Promise(function(resolve, reject) {
  803. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  804. page.grantedUsers = [];
  805. }
  806. page.grantedUsers.push(userData);
  807. page.save(function(err, data) {
  808. if (err) {
  809. return reject(err);
  810. }
  811. return resolve(data);
  812. });
  813. });
  814. };
  815. pageSchema.statics.pushRevision = async function(pageData, newRevision, user) {
  816. await newRevision.save();
  817. debug('Successfully saved new revision', newRevision);
  818. pageData.revision = newRevision;
  819. pageData.lastUpdateUser = user;
  820. pageData.updatedAt = Date.now();
  821. return pageData.save();
  822. };
  823. pageSchema.statics.create = function(path, body, user, options = {}) {
  824. validateCrowi();
  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. validateCrowi();
  877. const Page = this
  878. , Revision = crowi.model('Revision')
  879. , grant = options.grant || null
  880. , grantUserGroupId = options.grantUserGroupId || null
  881. , isSyncRevisionToHackmd = options.isSyncRevisionToHackmd
  882. , socketClientId = options.socketClientId || null
  883. ;
  884. // update existing page
  885. const newRevision = await Revision.prepareRevision(pageData, body, user);
  886. const revision = await Page.pushRevision(pageData, newRevision, user);
  887. let savedPage = await Page.findPageByPath(revision.path).populate('revision').populate('creator');
  888. if (grant != null) {
  889. const grantData = await Page.updateGrant(savedPage, grant, user, grantUserGroupId);
  890. debug('Page grant update:', grantData);
  891. }
  892. if (isSyncRevisionToHackmd) {
  893. savedPage = await Page.syncRevisionToHackmd(savedPage);
  894. }
  895. if (socketClientId != null) {
  896. pageEvent.emit('update', savedPage, user, socketClientId);
  897. }
  898. return savedPage;
  899. };
  900. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  901. const Page = this
  902. , newPath = Page.getDeletedPageName(pageData.path)
  903. , isTrashed = checkIfTrashed(pageData.path)
  904. , socketClientId = options.socketClientId || null
  905. ;
  906. if (Page.isDeletableName(pageData.path)) {
  907. if (isTrashed) {
  908. return Page.completelyDeletePage(pageData, user, options);
  909. }
  910. let updatedPageData = await Page.rename(pageData, newPath, user, {createRedirectPage: true});
  911. await Page.updatePageProperty(updatedPageData, {status: STATUS_DELETED, lastUpdateUser: user});
  912. if (socketClientId != null) {
  913. pageEvent.emit('delete', updatedPageData, user, socketClientId);
  914. }
  915. return updatedPageData;
  916. }
  917. else {
  918. return Promise.reject('Page is not deletable.');
  919. }
  920. };
  921. const checkIfTrashed = (path) => {
  922. return (path.search(/^\/trash/) !== -1);
  923. };
  924. pageSchema.statics.deletePageRecursively = function(pageData, user, options) {
  925. const Page = this
  926. , path = pageData.path
  927. , isTrashed = checkIfTrashed(pageData.path)
  928. ;
  929. options = options || {};
  930. if (isTrashed) {
  931. return Page.completelyDeletePageRecursively(pageData, user, options);
  932. }
  933. return Page.generateQueryToListWithDescendants(path, user, options)
  934. .then(function(pages) {
  935. return Promise.all(pages.map(function(page) {
  936. return Page.deletePage(page, user, options);
  937. }));
  938. })
  939. .then(function(data) {
  940. return pageData;
  941. });
  942. };
  943. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  944. const Page = this
  945. , newPath = Page.getRevertDeletedPageName(pageData.path)
  946. ;
  947. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  948. // そのため、そいつは削除してOK
  949. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  950. return new Promise(function(resolve, reject) {
  951. Page.findPageByPath(newPath)
  952. .then(function(originPageData) {
  953. if (originPageData.redirectTo !== pageData.path) {
  954. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  955. }
  956. return Page.completelyDeletePage(originPageData, options);
  957. }).then(function(done) {
  958. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user});
  959. }).then(function(done) {
  960. pageData.status = STATUS_PUBLISHED;
  961. debug('Revert deleted the page, and rename again it', pageData, newPath);
  962. return Page.rename(pageData, newPath, user, {});
  963. }).then(function(done) {
  964. pageData.path = newPath;
  965. resolve(pageData);
  966. }).catch(reject);
  967. });
  968. };
  969. pageSchema.statics.revertDeletedPageRecursively = function(pageData, user, options = {}) {
  970. const Page = this
  971. , path = pageData.path
  972. ;
  973. options = Object.assign({ includeDeletedPage: true }, options);
  974. return new Promise(function(resolve, reject) {
  975. Page
  976. .generateQueryToListWithDescendants(path, user, options)
  977. .exec()
  978. .then(function(pages) {
  979. Promise.all(pages.map(function(page) {
  980. return Page.revertDeletedPage(page, user, options);
  981. }))
  982. .then(function(data) {
  983. return resolve(data[0]);
  984. });
  985. });
  986. });
  987. };
  988. /**
  989. * This is danger.
  990. */
  991. pageSchema.statics.completelyDeletePage = function(pageData, user, options = {}) {
  992. validateCrowi();
  993. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  994. const Bookmark = crowi.model('Bookmark')
  995. , Attachment = crowi.model('Attachment')
  996. , Comment = crowi.model('Comment')
  997. , Revision = crowi.model('Revision')
  998. , PageGroupRelation = crowi.model('PageGroupRelation')
  999. , Page = this
  1000. , pageId = pageData._id
  1001. , socketClientId = options.socketClientId || null
  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. if (socketClientId != null) {
  1021. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  1022. }
  1023. resolve(pageData);
  1024. }).catch(reject);
  1025. });
  1026. };
  1027. pageSchema.statics.completelyDeletePageRecursively = function(pageData, user, options = {}) {
  1028. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1029. const Page = this
  1030. , path = pageData.path
  1031. ;
  1032. options = Object.assign({ includeDeletedPage: true }, options);
  1033. return new Promise(function(resolve, reject) {
  1034. Page
  1035. .generateQueryToListWithDescendants(path, user, options)
  1036. .then(function(pages) {
  1037. Promise.all(pages.map(function(page) {
  1038. return Page.completelyDeletePage(page, user, options);
  1039. }))
  1040. .then(function(data) {
  1041. return resolve(data[0]);
  1042. });
  1043. });
  1044. });
  1045. };
  1046. pageSchema.statics.removePageById = function(pageId) {
  1047. var Page = this;
  1048. return new Promise(function(resolve, reject) {
  1049. Page.remove({_id: pageId}, function(err, done) {
  1050. debug('Remove phisiaclly, the page', pageId, err, done);
  1051. if (err) {
  1052. return reject(err);
  1053. }
  1054. resolve(done);
  1055. });
  1056. });
  1057. };
  1058. pageSchema.statics.removePageByPath = function(pagePath) {
  1059. var Page = this;
  1060. return Page.findPageByPath(pagePath)
  1061. .then(function(pageData) {
  1062. return Page.removePageById(pageData.id);
  1063. });
  1064. };
  1065. /**
  1066. * remove the page that is redirecting to specified `pagePath` recursively
  1067. * ex: when
  1068. * '/page1' redirects to '/page2' and
  1069. * '/page2' redirects to '/page3'
  1070. * and given '/page3',
  1071. * '/page1' and '/page2' will be removed
  1072. *
  1073. * @param {string} pagePath
  1074. */
  1075. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1076. var Page = this;
  1077. return Page.findPageByRedirectTo(pagePath)
  1078. .then((redirectOriginPageData) => {
  1079. // remove
  1080. return Page.removePageById(redirectOriginPageData.id)
  1081. // remove recursive
  1082. .then(() => {
  1083. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path);
  1084. });
  1085. })
  1086. .catch((err) => {
  1087. // do nothing if origin page doesn't exist
  1088. return Promise.resolve();
  1089. });
  1090. };
  1091. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1092. validateCrowi();
  1093. const Page = this
  1094. , Revision = crowi.model('Revision')
  1095. , path = pageData.path
  1096. , createRedirectPage = options.createRedirectPage || 0
  1097. , socketClientId = options.socketClientId || null
  1098. ;
  1099. // sanitize path
  1100. newPagePath = crowi.xss.process(newPagePath);
  1101. await Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user});
  1102. // reivisions の path を変更
  1103. await Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  1104. if (createRedirectPage) {
  1105. const body = 'redirect ' + newPagePath;
  1106. await Page.create(path, body, user, {redirectTo: newPagePath});
  1107. }
  1108. let updatedPageData = await Page.findOne({path: newPagePath});
  1109. pageEvent.emit('delete', pageData, user, socketClientId);
  1110. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1111. return updatedPageData;
  1112. };
  1113. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1114. validateCrowi();
  1115. const Page = this
  1116. , path = pageData.path
  1117. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1118. // sanitize path
  1119. newPagePathPrefix = crowi.xss.process(newPagePathPrefix);
  1120. return Page.generateQueryToListWithDescendants(path, user, options)
  1121. .then(function(pages) {
  1122. return Promise.all(pages.map(function(page) {
  1123. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1124. return Page.rename(page, newPagePath, user, options);
  1125. }));
  1126. })
  1127. .then(function() {
  1128. pageData.path = newPagePathPrefix;
  1129. return pageData;
  1130. });
  1131. };
  1132. /**
  1133. * associate GROWI page and HackMD page
  1134. * @param {Page} pageData
  1135. * @param {string} pageIdOnHackmd
  1136. */
  1137. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1138. if (pageData.pageIdOnHackmd != null) {
  1139. throw new Error(`'pageIdOnHackmd' of the page '${pageData.path}' is not empty`);
  1140. }
  1141. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1142. return this.syncRevisionToHackmd(pageData);
  1143. };
  1144. /**
  1145. * update revisionHackmdSynced
  1146. * @param {Page} pageData
  1147. * @param {bool} isSave whether save or not
  1148. */
  1149. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1150. pageData.revisionHackmdSynced = pageData.revision;
  1151. pageData.hasDraftOnHackmd = false;
  1152. let returnData = pageData;
  1153. if (isSave) {
  1154. returnData = pageData.save();
  1155. }
  1156. return returnData;
  1157. };
  1158. /**
  1159. * update hasDraftOnHackmd
  1160. * !! This will be invoked many time from many people !!
  1161. *
  1162. * @param {Page} pageData
  1163. * @param {Boolean} newValue
  1164. */
  1165. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1166. if (pageData.hasDraftOnHackmd === newValue) {
  1167. // do nothing when hasDraftOnHackmd equals to newValue
  1168. return;
  1169. }
  1170. pageData.hasDraftOnHackmd = newValue;
  1171. return pageData.save();
  1172. };
  1173. pageSchema.statics.getHistories = function() {
  1174. // TODO
  1175. return;
  1176. };
  1177. /**
  1178. * return path that added slash to the end for specified path
  1179. */
  1180. pageSchema.statics.addSlashOfEnd = function(path) {
  1181. let returnPath = path;
  1182. if (!path.match(/\/$/)) {
  1183. returnPath += '/';
  1184. }
  1185. return returnPath;
  1186. };
  1187. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1188. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1189. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1190. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1191. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1192. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1193. return mongoose.model('Page', pageSchema);
  1194. };