page.js 37 KB

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