page.js 38 KB

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