page.js 36 KB

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