page.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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. /^\/_.*/, // /_api/* and so on
  332. /^\/\-\/.*/,
  333. /^\/_r\/.*/,
  334. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  335. /\/{2,}/, // avoid miss in renaming
  336. /\s+\/\s+/, // avoid miss in renaming
  337. /.+\/edit$/,
  338. /.+\.md$/,
  339. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  340. ];
  341. var isCreatable = true;
  342. forbiddenPages.forEach(function(page) {
  343. var pageNameReg = new RegExp(page);
  344. if (name.match(pageNameReg)) {
  345. isCreatable = false;
  346. return ;
  347. }
  348. });
  349. return isCreatable;
  350. };
  351. pageSchema.statics.fixToCreatableName = function(path) {
  352. return path
  353. .replace(/\/\//g, '/')
  354. ;
  355. };
  356. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  357. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  358. cb(err, data);
  359. });
  360. };
  361. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  362. this
  363. .find({})
  364. .sort({updatedAt: -1})
  365. .skip(offset)
  366. .limit(limit)
  367. .exec(function(err, data) {
  368. cb(err, data);
  369. });
  370. };
  371. pageSchema.statics.findPageById = function(id) {
  372. var Page = this;
  373. return new Promise(function(resolve, reject) {
  374. Page.findOne({_id: id}, function(err, pageData) {
  375. if (err) {
  376. return reject(err);
  377. }
  378. if (pageData == null) {
  379. return reject(new Error('Page not found'));
  380. }
  381. return Page.populatePageData(pageData, null).then(resolve);
  382. });
  383. });
  384. };
  385. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  386. var Page = this;
  387. var PageGroupRelation = crowi.model('PageGroupRelation');
  388. var pageData = null;
  389. return new Promise(function(resolve, reject) {
  390. Page.findPageById(id)
  391. .then(function(result) {
  392. pageData = result;
  393. if (userData && !pageData.isGrantedFor(userData)) {
  394. return PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData);
  395. }
  396. else {
  397. return true;
  398. }
  399. }).then((checkResult) => {
  400. if (checkResult) {
  401. return resolve(pageData);
  402. }
  403. else {
  404. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  405. }
  406. }).catch(function(err) {
  407. return reject(err);
  408. });
  409. });
  410. };
  411. // find page and check if granted user
  412. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  413. var self = this;
  414. var PageGroupRelation = crowi.model('PageGroupRelation');
  415. return new Promise(function(resolve, reject) {
  416. self.findOne({path: path}, function(err, pageData) {
  417. if (err) {
  418. return reject(err);
  419. }
  420. if (pageData === null) {
  421. if (ignoreNotFound) {
  422. return resolve(null);
  423. }
  424. var pageNotFoundError = new Error('Page Not Found');
  425. pageNotFoundError.name = 'Crowi:Page:NotFound';
  426. return reject(pageNotFoundError);
  427. }
  428. if (!pageData.isGrantedFor(userData)) {
  429. PageGroupRelation.isExistsGrantedGroupForPageAndUser(pageData, userData)
  430. .then(function(checkResult) {
  431. if (!checkResult) {
  432. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  433. }
  434. else {
  435. // return resolve(pageData);
  436. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  437. }
  438. })
  439. .catch(function(err) {
  440. return reject(err);
  441. });
  442. }
  443. else {
  444. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  445. }
  446. });
  447. });
  448. };
  449. // check if a given page has a local and global tempalte
  450. pageSchema.statics.checkIfTemplatesExist = function(path) {
  451. const Page = this;
  452. const pathList = generatePathsOnTree(path, []);
  453. const regexpList = pathList.map(path => new RegExp(`${path}/_{1,2}template`));
  454. let templateInfo = {
  455. localTemplateExists: false,
  456. globalTemplateExists: false,
  457. };
  458. return Page
  459. .find({path: {$in: regexpList}})
  460. .then(templates => {
  461. templateInfo.localTemplateExists = (assignTemplateByType(templates, path, '__') ? true : false);
  462. templateInfo.globalTemplateExists = (assignGlobalTemplate(templates, path) ? true : false);
  463. return templateInfo;
  464. });
  465. };
  466. /**
  467. * find all templates applicable to the new page
  468. */
  469. pageSchema.statics.findTemplate = function(path) {
  470. const Page = this;
  471. const templatePath = cutOffLastSlash(path);
  472. const pathList = generatePathsOnTree(templatePath, []);
  473. const regexpList = pathList.map(path => new RegExp(`${path}/_{1,2}template`));
  474. return Page
  475. .find({path: {$in: regexpList}})
  476. .populate({path: 'revision', model: 'Revision'})
  477. .then(templates => {
  478. return fetchTemplate(templates, templatePath);
  479. });
  480. };
  481. const cutOffLastSlash = path => {
  482. const lastSlash = path.lastIndexOf('/');
  483. return path.substr(0, lastSlash);
  484. };
  485. const generatePathsOnTree = (path, pathList) => {
  486. if (path === '') {
  487. return pathList;
  488. }
  489. pathList.push(path);
  490. const newPath = cutOffLastSlash(path);
  491. return generatePathsOnTree(newPath, pathList);
  492. };
  493. const assignTemplateByType = (templates, path, type) => {
  494. for (let i = 0; i < templates.length; i++) {
  495. if (templates[i].path === `${path}/${type}template`) {
  496. return templates[i];
  497. }
  498. }
  499. };
  500. const assignGlobalTemplate = (globalTemplates, path) => {
  501. const globalTemplate = assignTemplateByType(globalTemplates, path, '_');
  502. if (globalTemplate) {
  503. return globalTemplate;
  504. }
  505. if (path === '') {
  506. return;
  507. }
  508. const newPath = cutOffLastSlash(path);
  509. return assignGlobalTemplate(globalTemplates, newPath);
  510. };
  511. const fetchTemplate = (templates, templatePath) => {
  512. let templateBody;
  513. /**
  514. * get local template
  515. * @tempate: applicable only to immediate decendants
  516. */
  517. const localTemplate = assignTemplateByType(templates, templatePath, '__');
  518. /**
  519. * get global templates
  520. * _tempate: applicable to all pages under
  521. */
  522. const globalTemplate = assignGlobalTemplate(templates, templatePath);
  523. if (localTemplate) {
  524. templateBody = localTemplate.revision.body;
  525. }
  526. else if (globalTemplate) {
  527. templateBody = globalTemplate.revision.body;
  528. }
  529. return templateBody;
  530. };
  531. // find page by path
  532. pageSchema.statics.findPageByPath = function(path) {
  533. var Page = this;
  534. return new Promise(function(resolve, reject) {
  535. Page.findOne({path: path}, function(err, pageData) {
  536. if (err || pageData === null) {
  537. return reject(err);
  538. }
  539. return resolve(pageData);
  540. });
  541. });
  542. };
  543. pageSchema.statics.findListByPageIds = function(ids, options) {
  544. var Page = this;
  545. var User = crowi.model('User');
  546. var options = options || {}
  547. , limit = options.limit || 50
  548. , offset = options.skip || 0
  549. ;
  550. return new Promise(function(resolve, reject) {
  551. Page
  552. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  553. //.sort({createdAt: -1}) // TODO optionize
  554. .skip(offset)
  555. .limit(limit)
  556. .populate([
  557. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  558. {path: 'revision', model: 'Revision'},
  559. ])
  560. .exec(function(err, pages) {
  561. if (err) {
  562. return reject(err);
  563. }
  564. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  565. if (err) {
  566. return reject(err);
  567. }
  568. return resolve(data);
  569. });
  570. });
  571. });
  572. };
  573. pageSchema.statics.findPageByRedirectTo = function(path) {
  574. var Page = this;
  575. return new Promise(function(resolve, reject) {
  576. Page.findOne({redirectTo: path}, function(err, pageData) {
  577. if (err || pageData === null) {
  578. return reject(err);
  579. }
  580. return resolve(pageData);
  581. });
  582. });
  583. };
  584. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  585. var Page = this;
  586. var User = crowi.model('User');
  587. var limit = option.limit || 50;
  588. var offset = option.offset || 0;
  589. var conditions = {
  590. creator: user._id,
  591. redirectTo: null,
  592. $or: [
  593. {status: null},
  594. {status: STATUS_PUBLISHED},
  595. ],
  596. };
  597. if (!user.equals(currentUser._id)) {
  598. conditions.grant = GRANT_PUBLIC;
  599. }
  600. return new Promise(function(resolve, reject) {
  601. Page
  602. .find(conditions)
  603. .sort({createdAt: -1})
  604. .skip(offset)
  605. .limit(limit)
  606. .populate('revision')
  607. .exec()
  608. .then(function(pages) {
  609. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  610. });
  611. });
  612. };
  613. /**
  614. * Bulk get (for internal only)
  615. */
  616. pageSchema.statics.getStreamOfFindAll = function(options) {
  617. var Page = this
  618. , options = options || {}
  619. , publicOnly = options.publicOnly || true
  620. , criteria = {redirectTo: null, }
  621. ;
  622. if (publicOnly) {
  623. criteria.grant = GRANT_PUBLIC;
  624. }
  625. return this.find(criteria)
  626. .populate([
  627. {path: 'creator', model: 'User'},
  628. {path: 'revision', model: 'Revision'},
  629. ])
  630. .sort({updatedAt: -1})
  631. .cursor();
  632. };
  633. /**
  634. * find the page that is match with `path` and its descendants
  635. */
  636. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  637. var Page = this;
  638. // ignore other pages than descendants
  639. path = Page.addSlashOfEnd(path);
  640. // add option to escape the regex strings
  641. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  642. return Page.findListByStartWith(path, userData, combinedOption);
  643. };
  644. /**
  645. * find pages that start with `path`
  646. *
  647. * see the comment of `generateQueryToListByStartWith` function
  648. */
  649. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  650. var Page = this;
  651. var User = crowi.model('User');
  652. if (!option) {
  653. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  654. }
  655. var opt = {
  656. sort: option.sort || 'updatedAt',
  657. desc: option.desc || -1,
  658. offset: option.offset || 0,
  659. limit: option.limit || 50
  660. };
  661. var sortOpt = {};
  662. sortOpt[opt.sort] = opt.desc;
  663. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  664. return new Promise(function(resolve, reject) {
  665. var q = Page.generateQueryToListByStartWith(path, userData, option)
  666. .sort(sortOpt)
  667. .skip(opt.offset)
  668. .limit(opt.limit);
  669. // retrieve revision data
  670. if (isPopulateRevisionBody) {
  671. q = q.populate('revision');
  672. }
  673. else {
  674. q = q.populate('revision', '-body'); // exclude body
  675. }
  676. q.exec()
  677. .then(function(pages) {
  678. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  679. .then(resolve)
  680. .catch(reject);
  681. });
  682. });
  683. };
  684. /**
  685. * generate the query to find the page that is match with `path` and its descendants
  686. */
  687. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  688. var Page = this;
  689. // ignore other pages than descendants
  690. path = Page.addSlashOfEnd(path);
  691. // add option to escape the regex strings
  692. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  693. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  694. };
  695. /**
  696. * generate the query to find pages that start with `path`
  697. *
  698. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  699. * -> returns '{path}/*' and '{path}' self.
  700. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  701. * -> returns '{path}*'
  702. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  703. * -> returns '{path}*'
  704. *
  705. * *option*
  706. * - includeDeletedPage -- if true, search deleted pages (default: false)
  707. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  708. */
  709. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  710. var Page = this;
  711. var pathCondition = [];
  712. var includeDeletedPage = option.includeDeletedPage || false;
  713. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  714. /*
  715. * 1. add condition for finding the page completely match with `path` w/o last slash
  716. */
  717. let pathSlashOmitted = path;
  718. if (path.match(/\/$/)) {
  719. pathSlashOmitted = path.substr(0, path.length -1);
  720. pathCondition.push({path: pathSlashOmitted});
  721. }
  722. /*
  723. * 2. add decendants
  724. */
  725. var pattern = (isRegExpEscapedFromPath)
  726. ? escapeStringRegexp(path) // escape
  727. : pathSlashOmitted;
  728. var queryReg = new RegExp('^' + pattern);
  729. pathCondition.push({path: queryReg});
  730. var q = Page.find({
  731. redirectTo: null,
  732. $or: [
  733. {grant: null},
  734. {grant: GRANT_PUBLIC},
  735. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  736. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  737. {grant: GRANT_OWNER, grantedUsers: userData._id},
  738. ], })
  739. .and({
  740. $or: pathCondition
  741. });
  742. if (!includeDeletedPage) {
  743. q.and({
  744. $or: [
  745. {status: null},
  746. {status: STATUS_PUBLISHED},
  747. ],
  748. });
  749. }
  750. return q;
  751. };
  752. pageSchema.statics.updatePageProperty = function(page, updateData) {
  753. var Page = this;
  754. return new Promise(function(resolve, reject) {
  755. // TODO foreach して save
  756. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  757. if (err) {
  758. return reject(err);
  759. }
  760. return resolve(data);
  761. });
  762. });
  763. };
  764. pageSchema.statics.updateGrant = function(page, grant, userData, grantUserGroupId) {
  765. var Page = this;
  766. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  767. throw new Error('grant userGroupId is not specified');
  768. }
  769. return new Promise(function(resolve, reject) {
  770. page.grant = grant;
  771. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  772. page.grantedUsers = [];
  773. }
  774. else {
  775. page.grantedUsers = [];
  776. page.grantedUsers.push(userData._id);
  777. }
  778. page.save(function(err, data) {
  779. debug('Page.updateGrant, saved grantedUsers.', err, data);
  780. if (err) {
  781. return reject(err);
  782. }
  783. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  784. .then(() => {
  785. return resolve(data);
  786. });
  787. });
  788. });
  789. };
  790. pageSchema.statics.updateGrantUserGroup = function(page, grant, grantUserGroupId, userData) {
  791. var UserGroupRelation = crowi.model('UserGroupRelation');
  792. var PageGroupRelation = crowi.model('PageGroupRelation');
  793. // グループの場合
  794. if (grant == GRANT_USER_GROUP) {
  795. debug('grant is usergroup', grantUserGroupId);
  796. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  797. .then((relation) => {
  798. if (relation == null) {
  799. return reject(new Error('no relations were exist for group and user.'));
  800. }
  801. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  802. })
  803. .catch((err) => {
  804. return reject(new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId));
  805. });
  806. }
  807. else {
  808. return PageGroupRelation.removeAllByPage(page);
  809. }
  810. };
  811. // Instance method でいいのでは
  812. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  813. return new Promise(function(resolve, reject) {
  814. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  815. page.grantedUsers = [];
  816. }
  817. page.grantedUsers.push(userData);
  818. page.save(function(err, data) {
  819. if (err) {
  820. return reject(err);
  821. }
  822. return resolve(data);
  823. });
  824. });
  825. };
  826. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  827. var isCreate = false;
  828. if (pageData.revision === undefined) {
  829. debug('pushRevision on Create');
  830. isCreate = true;
  831. }
  832. return new Promise(function(resolve, reject) {
  833. newRevision.save(function(err, newRevision) {
  834. if (err) {
  835. debug('Error on saving revision', err);
  836. return reject(err);
  837. }
  838. debug('Successfully saved new revision', newRevision);
  839. pageData.revision = newRevision;
  840. pageData.lastUpdateUser = user;
  841. pageData.updatedAt = Date.now();
  842. pageData.save(function(err, data) {
  843. if (err) {
  844. // todo: remove new revision?
  845. debug('Error on save page data (after push revision)', err);
  846. return reject(err);
  847. }
  848. resolve(data);
  849. if (!isCreate) {
  850. debug('pushRevision on Update');
  851. }
  852. });
  853. });
  854. });
  855. };
  856. pageSchema.statics.create = function(path, body, user, options) {
  857. var Page = this
  858. , Revision = crowi.model('Revision')
  859. , format = options.format || 'markdown'
  860. , grant = options.grant || GRANT_PUBLIC
  861. , redirectTo = options.redirectTo || null
  862. , grantUserGroupId = options.grantUserGroupId || null;
  863. // force public
  864. if (isPortalPath(path)) {
  865. grant = GRANT_PUBLIC;
  866. }
  867. return new Promise(function(resolve, reject) {
  868. Page.findOne({path: path}, function(err, pageData) {
  869. if (pageData) {
  870. return reject(new Error('Cannot create new page to existed path'));
  871. }
  872. var newPage = new Page();
  873. newPage.path = path;
  874. newPage.creator = user;
  875. newPage.lastUpdateUser = user;
  876. newPage.createdAt = Date.now();
  877. newPage.updatedAt = Date.now();
  878. newPage.redirectTo = redirectTo;
  879. newPage.grant = grant;
  880. newPage.status = STATUS_PUBLISHED;
  881. newPage.grantedUsers = [];
  882. newPage.grantedUsers.push(user);
  883. newPage.save(function(err, newPage) {
  884. if (err) {
  885. return reject(err);
  886. }
  887. if (newPage.grant == Page.GRANT_USER_GROUP && grantUserGroupId != null) {
  888. Page.updateGrantUserGroup(newPage, grant, grantUserGroupId, user)
  889. .catch((err) => {
  890. return reject(err);
  891. });
  892. }
  893. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  894. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  895. resolve(data);
  896. pageEvent.emit('create', data, user);
  897. }).catch(function(err) {
  898. debug('Push Revision Error on create page', err);
  899. return reject(err);
  900. });
  901. });
  902. });
  903. });
  904. };
  905. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  906. var Page = this
  907. , Revision = crowi.model('Revision')
  908. , grant = options.grant || null
  909. , grantUserGroupId = options.grantUserGroupId || null
  910. ;
  911. // update existing page
  912. var newRevision = Revision.prepareRevision(pageData, body, user);
  913. return new Promise(function(resolve, reject) {
  914. Page.pushRevision(pageData, newRevision, user)
  915. .then(function(revision) {
  916. if (grant != pageData.grant) {
  917. return Page.updateGrant(pageData, grant, user, grantUserGroupId).then(function(data) {
  918. debug('Page grant update:', data);
  919. resolve(data);
  920. pageEvent.emit('update', data, user);
  921. });
  922. }
  923. else {
  924. resolve(pageData);
  925. pageEvent.emit('update', pageData, user);
  926. }
  927. }).catch(function(err) {
  928. debug('Error on update', err);
  929. debug('Error on update', err.stack);
  930. });
  931. });
  932. };
  933. pageSchema.statics.deletePage = function(pageData, user, options) {
  934. var Page = this
  935. , newPath = Page.getDeletedPageName(pageData.path)
  936. ;
  937. if (Page.isDeletableName(pageData.path)) {
  938. return new Promise(function(resolve, reject) {
  939. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  940. .then(function(data) {
  941. pageData.status = STATUS_DELETED;
  942. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  943. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  944. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  945. debug('Deleted the page, and rename it', pageData.path, newPath);
  946. return Page.rename(pageData, newPath, user, {createRedirectPage: true});
  947. }).then(function(pageData) {
  948. resolve(pageData);
  949. }).catch(reject);
  950. });
  951. }
  952. else {
  953. return Promise.reject('Page is not deletable.');
  954. }
  955. };
  956. pageSchema.statics.deletePageRecursively = function(pageData, user, options) {
  957. var Page = this
  958. , path = pageData.path
  959. , options = options || {}
  960. ;
  961. return new Promise(function(resolve, reject) {
  962. Page
  963. .generateQueryToListWithDescendants(path, user, options)
  964. .then(function(pages) {
  965. Promise.all(pages.map(function(page) {
  966. return Page.deletePage(page, user, options);
  967. }))
  968. .then(function(data) {
  969. return resolve(pageData);
  970. });
  971. });
  972. });
  973. };
  974. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  975. var Page = this
  976. , newPath = Page.getRevertDeletedPageName(pageData.path)
  977. ;
  978. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  979. // そのため、そいつは削除してOK
  980. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  981. return new Promise(function(resolve, reject) {
  982. Page.findPageByPath(newPath)
  983. .then(function(originPageData) {
  984. if (originPageData.redirectTo !== pageData.path) {
  985. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  986. }
  987. return Page.completelyDeletePage(originPageData);
  988. }).then(function(done) {
  989. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user});
  990. }).then(function(done) {
  991. pageData.status = STATUS_PUBLISHED;
  992. debug('Revert deleted the page, and rename again it', pageData, newPath);
  993. return Page.rename(pageData, newPath, user, {});
  994. }).then(function(done) {
  995. pageData.path = newPath;
  996. resolve(pageData);
  997. }).catch(reject);
  998. });
  999. };
  1000. pageSchema.statics.revertDeletedPageRecursively = function(pageData, user, options) {
  1001. var Page = this
  1002. , path = pageData.path
  1003. , options = options || { includeDeletedPage: true}
  1004. ;
  1005. return new Promise(function(resolve, reject) {
  1006. Page
  1007. .generateQueryToListWithDescendants(path, user, options)
  1008. .then(function(pages) {
  1009. Promise.all(pages.map(function(page) {
  1010. return Page.revertDeletedPage(page, user, options);
  1011. }))
  1012. .then(function(data) {
  1013. return resolve(data[0]);
  1014. });
  1015. });
  1016. });
  1017. };
  1018. /**
  1019. * This is danger.
  1020. */
  1021. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  1022. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1023. var Bookmark = crowi.model('Bookmark')
  1024. , Attachment = crowi.model('Attachment')
  1025. , Comment = crowi.model('Comment')
  1026. , Revision = crowi.model('Revision')
  1027. , Page = this
  1028. , pageId = pageData._id
  1029. ;
  1030. debug('Completely delete', pageData.path);
  1031. return new Promise(function(resolve, reject) {
  1032. Bookmark.removeBookmarksByPageId(pageId)
  1033. .then(function(done) {
  1034. }).then(function(done) {
  1035. return Attachment.removeAttachmentsByPageId(pageId);
  1036. }).then(function(done) {
  1037. return Comment.removeCommentsByPageId(pageId);
  1038. }).then(function(done) {
  1039. return Revision.removeRevisionsByPath(pageData.path);
  1040. }).then(function(done) {
  1041. return Page.removePageById(pageId);
  1042. }).then(function(done) {
  1043. return Page.removeRedirectOriginPageByPath(pageData.path);
  1044. }).then(function(done) {
  1045. pageEvent.emit('delete', pageData, user); // update as renamed page
  1046. resolve(pageData);
  1047. }).catch(reject);
  1048. });
  1049. };
  1050. pageSchema.statics.completelyDeletePageRecursively = function(pageData, user, options) {
  1051. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1052. var Page = this
  1053. , path = pageData.path
  1054. , options = options || { includeDeletedPage: true }
  1055. ;
  1056. return new Promise(function(resolve, reject) {
  1057. Page
  1058. .generateQueryToListWithDescendants(path, user, options)
  1059. .then(function(pages) {
  1060. Promise.all(pages.map(function(page) {
  1061. return Page.completelyDeletePage(page, user, options);
  1062. }))
  1063. .then(function(data) {
  1064. return resolve(data[0]);
  1065. });
  1066. });
  1067. });
  1068. };
  1069. pageSchema.statics.removePageById = function(pageId) {
  1070. var Page = this;
  1071. return new Promise(function(resolve, reject) {
  1072. Page.remove({_id: pageId}, function(err, done) {
  1073. debug('Remove phisiaclly, the page', pageId, err, done);
  1074. if (err) {
  1075. return reject(err);
  1076. }
  1077. resolve(done);
  1078. });
  1079. });
  1080. };
  1081. pageSchema.statics.removePageByPath = function(pagePath) {
  1082. var Page = this;
  1083. return Page.findPageByPath(pagePath)
  1084. .then(function(pageData) {
  1085. return Page.removePageById(pageData.id);
  1086. });
  1087. };
  1088. /**
  1089. * remove the page that is redirecting to specified `pagePath` recursively
  1090. * ex: when
  1091. * '/page1' redirects to '/page2' and
  1092. * '/page2' redirects to '/page3'
  1093. * and given '/page3',
  1094. * '/page1' and '/page2' will be removed
  1095. *
  1096. * @param {string} pagePath
  1097. */
  1098. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1099. var Page = this;
  1100. return Page.findPageByRedirectTo(pagePath)
  1101. .then((redirectOriginPageData) => {
  1102. // remove
  1103. return Page.removePageById(redirectOriginPageData.id)
  1104. // remove recursive
  1105. .then(() => {
  1106. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path);
  1107. });
  1108. })
  1109. .catch((err) => {
  1110. // do nothing if origin page doesn't exist
  1111. return Promise.resolve();
  1112. });
  1113. };
  1114. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1115. var Page = this
  1116. , Revision = crowi.model('Revision')
  1117. , path = pageData.path
  1118. , createRedirectPage = options.createRedirectPage || 0
  1119. , moveUnderTrees = options.moveUnderTrees || 0;
  1120. return new Promise(function(resolve, reject) {
  1121. // pageData の path を変更
  1122. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  1123. .then(function(data) {
  1124. // reivisions の path を変更
  1125. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  1126. }).then(function(data) {
  1127. pageData.path = newPagePath;
  1128. if (createRedirectPage) {
  1129. var body = 'redirect ' + newPagePath;
  1130. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  1131. }
  1132. else {
  1133. resolve(data);
  1134. }
  1135. pageEvent.emit('update', pageData, user); // update as renamed page
  1136. });
  1137. });
  1138. };
  1139. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1140. var Page = this
  1141. , path = pageData.path
  1142. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1143. return new Promise(function(resolve, reject) {
  1144. Page
  1145. .generateQueryToListWithDescendants(path, user, options)
  1146. .then(function(pages) {
  1147. Promise.all(pages.map(function(page) {
  1148. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1149. return Page.rename(page, newPagePath, user, options);
  1150. }))
  1151. .then(function() {
  1152. pageData.path = newPagePathPrefix;
  1153. return resolve();
  1154. });
  1155. });
  1156. });
  1157. };
  1158. pageSchema.statics.getHistories = function() {
  1159. // TODO
  1160. return;
  1161. };
  1162. /**
  1163. * return path that added slash to the end for specified path
  1164. */
  1165. pageSchema.statics.addSlashOfEnd = function(path) {
  1166. let returnPath = path;
  1167. if (!path.match(/\/$/)) {
  1168. returnPath += '/';
  1169. }
  1170. return returnPath;
  1171. };
  1172. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1173. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1174. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1175. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1176. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1177. return mongoose.model('Page', pageSchema);
  1178. };