index.ts 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518
  1. import type EventEmitter from 'events';
  2. import pathlib from 'path';
  3. import { Readable, Writable } from 'stream';
  4. import type {
  5. Ref, HasObjectId, IUserHasId, IUser,
  6. IPage, IPageInfo, IPageInfoAll, IPageInfoForEntity, IPageWithMeta, IGrantedGroup, IRevisionHasId,
  7. } from '@growi/core';
  8. import {
  9. PageGrant, PageStatus, getIdForRef,
  10. } from '@growi/core';
  11. import {
  12. pagePathUtils, pathUtils,
  13. } from '@growi/core/dist/utils';
  14. import escapeStringRegexp from 'escape-string-regexp';
  15. import type { ObjectId, Cursor } from 'mongoose';
  16. import mongoose from 'mongoose';
  17. import streamToPromise from 'stream-to-promise';
  18. import { Comment } from '~/features/comment/server';
  19. import type { ExternalUserGroupDocument } from '~/features/external-user-group/server/models/external-user-group';
  20. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  21. import { SupportedAction } from '~/interfaces/activity';
  22. import { V5ConversionErrCode } from '~/interfaces/errors/v5-conversion-error';
  23. import type { IOptionsForCreate, IOptionsForUpdate } from '~/interfaces/page';
  24. import type { IPageDeleteConfigValueToProcessValidation } from '~/interfaces/page-delete-config';
  25. import {
  26. PageDeleteConfigValue, PageSingleDeleteCompConfigValue,
  27. } from '~/interfaces/page-delete-config';
  28. import type { PopulatedGrantedGroup } from '~/interfaces/page-grant';
  29. import {
  30. type IPageOperationProcessInfo, type IPageOperationProcessData, PageActionStage, PageActionType,
  31. } from '~/interfaces/page-operation';
  32. import { PageActionOnGroupDelete } from '~/interfaces/user-group';
  33. import { SocketEventName, type PageMigrationErrorData, type UpdateDescCountRawData } from '~/interfaces/websocket';
  34. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  35. import type { CreateMethod } from '~/server/models/page';
  36. import {
  37. type PageModel, type PageDocument, pushRevision, PageQueryBuilder,
  38. } from '~/server/models/page';
  39. import type { PageTagRelationDocument } from '~/server/models/page-tag-relation';
  40. import PageTagRelation from '~/server/models/page-tag-relation';
  41. import type { UserGroupDocument } from '~/server/models/user-group';
  42. import { getYjsConnectionManager } from '~/server/service/yjs-connection-manager';
  43. import { createBatchStream } from '~/server/util/batch-stream';
  44. import { collectAncestorPaths } from '~/server/util/collect-ancestor-paths';
  45. import { generalXssFilter } from '~/services/general-xss-filter';
  46. import loggerFactory from '~/utils/logger';
  47. import { prepareDeleteConfigValuesForCalc } from '~/utils/page-delete-config';
  48. import type { ObjectIdLike } from '../../interfaces/mongoose-utils';
  49. import { Attachment } from '../../models';
  50. import { PathAlreadyExistsError } from '../../models/errors';
  51. import type { PageOperationDocument } from '../../models/page-operation';
  52. import PageOperation from '../../models/page-operation';
  53. import PageRedirect from '../../models/page-redirect';
  54. import { serializePageSecurely } from '../../models/serializers/page-serializer';
  55. import ShareLink from '../../models/share-link';
  56. import Subscription from '../../models/subscription';
  57. import UserGroupRelation from '../../models/user-group-relation';
  58. import { V5ConversionError } from '../../models/vo/v5-conversion-error';
  59. import { divideByType } from '../../util/granted-group';
  60. import { configManager } from '../config-manager';
  61. import type { IPageGrantService } from '../page-grant';
  62. import { preNotifyService } from '../pre-notify';
  63. import { BULK_REINDEX_SIZE, LIMIT_FOR_MULTIPLE_PAGE_OP } from './consts';
  64. import type { IPageService } from './page-service';
  65. import { shouldUseV4Process } from './should-use-v4-process';
  66. export * from './page-service';
  67. const debug = require('debug')('growi:services:page');
  68. const logger = loggerFactory('growi:services:page');
  69. const {
  70. isTrashPage, isTopPage, omitDuplicateAreaPageFromPages, getUsernameByPath,
  71. canMoveByPath, isUsersTopPage, isMovablePage, isUsersHomepage, hasSlash, generateChildrenRegExp,
  72. } = pagePathUtils;
  73. const { addTrailingSlash } = pathUtils;
  74. // TODO: improve type
  75. class PageCursorsForDescendantsFactory {
  76. private user: any; // TODO: Typescriptize model
  77. private rootPage: any; // TODO: wait for mongoose update
  78. private shouldIncludeEmpty: boolean;
  79. private initialCursor: Cursor<any> | never[]; // TODO: wait for mongoose update
  80. private Page: PageModel;
  81. constructor(user: any, rootPage: any, shouldIncludeEmpty: boolean) {
  82. this.user = user;
  83. this.rootPage = rootPage;
  84. this.shouldIncludeEmpty = shouldIncludeEmpty;
  85. this.Page = mongoose.model('Page') as unknown as PageModel;
  86. }
  87. // prepare initial cursor
  88. private async init() {
  89. const initialCursor = await this.generateCursorToFindChildren(this.rootPage);
  90. this.initialCursor = initialCursor;
  91. }
  92. /**
  93. * Returns Iterable that yields only descendant pages unorderedly
  94. * @returns Promise<AsyncGenerator>
  95. */
  96. async generateIterable(): Promise<AsyncGenerator | never[]> {
  97. // initialize cursor
  98. await this.init();
  99. return this.isNeverArray(this.initialCursor) ? [] : this.generateOnlyDescendants(this.initialCursor);
  100. }
  101. /**
  102. * Returns Readable that produces only descendant pages unorderedly
  103. * @returns Promise<Readable>
  104. */
  105. async generateReadable(): Promise<Readable> {
  106. return Readable.from(await this.generateIterable());
  107. }
  108. /**
  109. * Generator that unorderedly yields descendant pages
  110. */
  111. private async* generateOnlyDescendants(cursor: Cursor<any>) {
  112. for await (const page of cursor) {
  113. const nextCursor = await this.generateCursorToFindChildren(page);
  114. if (!this.isNeverArray(nextCursor)) {
  115. yield* this.generateOnlyDescendants(nextCursor); // recursively yield
  116. }
  117. yield page;
  118. }
  119. }
  120. private async generateCursorToFindChildren(page: any): Promise<Cursor<any> | never[]> {
  121. if (page == null) {
  122. return [];
  123. }
  124. const { PageQueryBuilder } = this.Page;
  125. const builder = new PageQueryBuilder(this.Page.find(), this.shouldIncludeEmpty);
  126. builder.addConditionToFilteringByParentId(page._id);
  127. const cursor = builder.query.lean().cursor({ batchSize: BULK_REINDEX_SIZE }) as Cursor<any>;
  128. return cursor;
  129. }
  130. private isNeverArray(val: Cursor<any> | never[]): val is never[] {
  131. return 'length' in val && val.length === 0;
  132. }
  133. }
  134. class PageService implements IPageService {
  135. crowi: any;
  136. pageEvent: EventEmitter & {
  137. onCreate,
  138. onCreateMany,
  139. onAddSeenUsers,
  140. };
  141. tagEvent: any;
  142. activityEvent: any;
  143. pageGrantService: IPageGrantService;
  144. constructor(crowi) {
  145. this.crowi = crowi;
  146. this.pageEvent = crowi.event('page');
  147. this.tagEvent = crowi.event('tag');
  148. this.activityEvent = crowi.event('activity');
  149. this.pageGrantService = crowi.pageGrantService;
  150. // init
  151. this.initPageEvent();
  152. this.canDeleteCompletely = this.canDeleteCompletely.bind(this);
  153. this.canDelete = this.canDelete.bind(this);
  154. }
  155. private initPageEvent() {
  156. // create
  157. this.pageEvent.on('create', this.pageEvent.onCreate);
  158. // createMany
  159. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  160. this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
  161. }
  162. getEventEmitter(): EventEmitter {
  163. return this.pageEvent;
  164. }
  165. /**
  166. * Check if page can be deleted completely.
  167. * Use the following methods before execution of canDeleteCompletely to get params.
  168. * - pageService.getCreatorIdForCanDelete: creatorId
  169. * - pageGrantService.getUserRelatedGroups: userRelatedGroups
  170. * Do NOT make this method async as for now, because canDeleteCompletely is called in /page-listing/info in a for loop,
  171. * and /page-listing/info should not be an execution heavy API.
  172. */
  173. canDeleteCompletely(
  174. page: PageDocument,
  175. creatorId: ObjectIdLike | null,
  176. operator: any | null,
  177. isRecursively: boolean,
  178. userRelatedGroups: PopulatedGrantedGroup[],
  179. ): boolean {
  180. if (operator == null || isTopPage(page.path) || isUsersTopPage(page.path)) return false;
  181. const pageCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
  182. const pageRecursiveCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageRecursiveCompleteDeletionAuthority');
  183. if (!this.canDeleteCompletelyAsMultiGroupGrantedPage(page, creatorId, operator, userRelatedGroups)) return false;
  184. const [singleAuthority, recursiveAuthority] = prepareDeleteConfigValuesForCalc(pageCompleteDeletionAuthority, pageRecursiveCompleteDeletionAuthority);
  185. return this.canDeleteLogic(creatorId, operator, isRecursively, singleAuthority, recursiveAuthority);
  186. }
  187. /**
  188. * If page is multi-group granted, check if operator is allowed to completely delete the page.
  189. * see: https://dev.growi.org/656745fa52eafe1cf1879508#%E5%AE%8C%E5%85%A8%E3%81%AB%E5%89%8A%E9%99%A4%E3%81%99%E3%82%8B%E6%93%8D%E4%BD%9C
  190. * creatorId must be obtained by getCreatorIdForCanDelete
  191. */
  192. canDeleteCompletelyAsMultiGroupGrantedPage(
  193. page: PageDocument, creatorId: ObjectIdLike | null, operator: any | null, userRelatedGroups: PopulatedGrantedGroup[],
  194. ): boolean {
  195. const pageCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
  196. const isAllGroupMembershipRequiredForPageCompleteDeletion = this.crowi.configManager.getConfig(
  197. 'crowi', 'security:isAllGroupMembershipRequiredForPageCompleteDeletion',
  198. );
  199. const isAdmin = operator?.admin ?? false;
  200. const isAuthor = operator?._id == null ? false : operator._id.equals(creatorId);
  201. const isAdminOrAuthor = isAdmin || isAuthor;
  202. if (page.grant === PageGrant.GRANT_USER_GROUP
  203. && !isAdminOrAuthor && pageCompleteDeletionAuthority === PageSingleDeleteCompConfigValue.Anyone
  204. && isAllGroupMembershipRequiredForPageCompleteDeletion) {
  205. const userRelatedGrantedGroups = this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(userRelatedGroups, page);
  206. if (userRelatedGrantedGroups.length !== page.grantedGroups.length) {
  207. return false;
  208. }
  209. }
  210. return true;
  211. }
  212. // When page is empty, the 'canDelete' judgement should be done using the creator of the closest non-empty ancestor page.
  213. async getCreatorIdForCanDelete(page: PageDocument): Promise<ObjectIdLike | null> {
  214. if (page.isEmpty) {
  215. const Page = mongoose.model<IPage, PageModel>('Page');
  216. const notEmptyClosestAncestor = await Page.findNonEmptyClosestAncestor(page.path);
  217. return notEmptyClosestAncestor?.creator == null
  218. ? null
  219. : getIdForRef(notEmptyClosestAncestor.creator);
  220. }
  221. return page.creator == null
  222. ? null
  223. : getIdForRef(page.creator);
  224. }
  225. // Use getCreatorIdForCanDelete before execution of canDelete to get creatorId.
  226. canDelete(page: PageDocument, creatorId: ObjectIdLike | null, operator: any | null, isRecursively: boolean): boolean {
  227. if (operator == null || isTopPage(page.path) || isUsersTopPage(page.path)) return false;
  228. const pageDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageDeletionAuthority');
  229. const pageRecursiveDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageRecursiveDeletionAuthority');
  230. const [singleAuthority, recursiveAuthority] = prepareDeleteConfigValuesForCalc(pageDeletionAuthority, pageRecursiveDeletionAuthority);
  231. return this.canDeleteLogic(creatorId, operator, isRecursively, singleAuthority, recursiveAuthority);
  232. }
  233. canDeleteUserHomepageByConfig(): boolean {
  234. return configManager.getConfig('crowi', 'security:user-homepage-deletion:isEnabled') ?? false;
  235. }
  236. async isUsersHomepageOwnerAbsent(path: string): Promise<boolean> {
  237. const User = mongoose.model('User');
  238. const username = getUsernameByPath(path);
  239. if (username == null) {
  240. throw new Error('Cannot found username by path');
  241. }
  242. const ownerExists = await User.exists({ username });
  243. return ownerExists === null;
  244. }
  245. private canDeleteLogic(
  246. creatorId: ObjectIdLike | null,
  247. operator,
  248. isRecursively: boolean,
  249. authority: IPageDeleteConfigValueToProcessValidation | null,
  250. recursiveAuthority: IPageDeleteConfigValueToProcessValidation | null,
  251. ): boolean {
  252. const isAdmin = operator?.admin ?? false;
  253. const isAuthor = operator?._id == null ? false : operator._id.equals(creatorId);
  254. if (isRecursively) {
  255. return this.compareDeleteConfig(isAdmin, isAuthor, recursiveAuthority);
  256. }
  257. return this.compareDeleteConfig(isAdmin, isAuthor, authority);
  258. }
  259. private compareDeleteConfig(isAdmin: boolean, isAuthor: boolean, authority: IPageDeleteConfigValueToProcessValidation | null): boolean {
  260. if (isAdmin) {
  261. return true;
  262. }
  263. if (authority === PageDeleteConfigValue.Anyone || authority == null) {
  264. return true;
  265. }
  266. if (authority === PageDeleteConfigValue.AdminAndAuthor && isAuthor) {
  267. return true;
  268. }
  269. return false;
  270. }
  271. private async getAbsenseUserHomeList(pages: PageDocument[]): Promise<string[]> {
  272. const userHomepages = pages.filter(p => isUsersHomepage(p.path));
  273. const User = mongoose.model<IUser>('User');
  274. const usernames = userHomepages
  275. .map(page => getUsernameByPath(page.path))
  276. // see: https://zenn.dev/kimuson/articles/filter_safety_type_guard
  277. .filter((username): username is Exclude<typeof username, null> => username !== null);
  278. const existingUsernames = await User.distinct<string>('username', { username: { $in: usernames } });
  279. return userHomepages.filter((page) => {
  280. const username = getUsernameByPath(page.path);
  281. if (username == null) {
  282. throw new Error('Cannot found username by path');
  283. }
  284. return !existingUsernames.includes(username);
  285. }).map(p => p.path);
  286. }
  287. private async filterPages(
  288. pages: PageDocument[],
  289. user: IUserHasId,
  290. isRecursively: boolean,
  291. canDeleteFunction: (
  292. page: PageDocument, creatorId: ObjectIdLike | null, operator: any, isRecursively: boolean, userRelatedGroups: PopulatedGrantedGroup[]
  293. ) => boolean,
  294. ): Promise<PageDocument[]> {
  295. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  296. const filteredPages = pages.filter(async(p) => {
  297. if (p.isEmpty) return true;
  298. const canDelete = canDeleteFunction(
  299. p,
  300. p.creator == null ? null : getIdForRef(p.creator),
  301. user,
  302. isRecursively,
  303. userRelatedGroups,
  304. );
  305. return canDelete;
  306. });
  307. if (!this.canDeleteUserHomepageByConfig()) {
  308. return filteredPages.filter(p => !isUsersHomepage(p.path));
  309. }
  310. // Confirmation of deletion of user homepages is an asynchronous process,
  311. // so it is processed separately for performance optimization.
  312. const absenseUserHomeList = await this.getAbsenseUserHomeList(filteredPages);
  313. const excludeActiveUserHomepage = (path: string) => {
  314. if (!isUsersHomepage(path)) {
  315. return true;
  316. }
  317. return absenseUserHomeList.includes(path);
  318. };
  319. return filteredPages
  320. .filter(p => excludeActiveUserHomepage(p.path));
  321. }
  322. async filterPagesByCanDeleteCompletely(pages: PageDocument[], user: IUserHasId, isRecursively: boolean): Promise<PageDocument[]> {
  323. return this.filterPages(pages, user, isRecursively, this.canDeleteCompletely);
  324. }
  325. async filterPagesByCanDelete(pages: PageDocument[], user: IUserHasId, isRecursively: boolean): Promise<PageDocument[]> {
  326. return this.filterPages(pages, user, isRecursively, this.canDelete);
  327. }
  328. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  329. async findPageAndMetaDataByViewer(
  330. pageId: string, path: string, user: IUserHasId, includeEmpty = false, isSharedPage = false,
  331. ): Promise<IPageWithMeta<IPageInfoAll>|null> {
  332. const Page = this.crowi.model('Page') as PageModel;
  333. let page: PageDocument & HasObjectId | null;
  334. if (pageId != null) { // prioritized
  335. page = await Page.findByIdAndViewer(pageId, user, null, includeEmpty);
  336. }
  337. else {
  338. page = await Page.findByPathAndViewer(path, user, null, true, includeEmpty);
  339. }
  340. if (page == null) {
  341. return null;
  342. }
  343. if (isSharedPage) {
  344. return {
  345. data: page,
  346. meta: {
  347. isV5Compatible: isTopPage(page.path) || page.parent != null,
  348. isEmpty: page.isEmpty,
  349. isMovable: false,
  350. isDeletable: false,
  351. isAbleToDeleteCompletely: false,
  352. isRevertible: false,
  353. },
  354. };
  355. }
  356. const isGuestUser = user == null;
  357. const pageInfo = this.constructBasicPageInfo(page, isGuestUser);
  358. const Bookmark = this.crowi.model('Bookmark');
  359. const bookmarkCount = await Bookmark.countByPageId(pageId);
  360. const metadataForGuest = {
  361. ...pageInfo,
  362. bookmarkCount,
  363. };
  364. if (isGuestUser) {
  365. return {
  366. data: page,
  367. meta: metadataForGuest,
  368. };
  369. }
  370. const isBookmarked: boolean = (await Bookmark.findByPageIdAndUserId(pageId, user._id)) != null;
  371. const isLiked: boolean = page.isLiked(user);
  372. const subscription = await Subscription.findByUserIdAndTargetId(user._id, pageId);
  373. const creatorId = await this.getCreatorIdForCanDelete(page);
  374. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  375. const isDeletable = this.canDelete(page, creatorId, user, false);
  376. const isAbleToDeleteCompletely = this.canDeleteCompletely(page, creatorId, user, false, userRelatedGroups); // use normal delete config
  377. return {
  378. data: page,
  379. meta: {
  380. ...metadataForGuest,
  381. isDeletable,
  382. isAbleToDeleteCompletely,
  383. isBookmarked,
  384. isLiked,
  385. subscriptionStatus: subscription?.status,
  386. },
  387. };
  388. }
  389. private shouldUseV4ProcessForRevert(page): boolean {
  390. const Page = mongoose.model('Page') as unknown as PageModel;
  391. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  392. const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
  393. const shouldUseV4Process = !isV5Compatible || isPageRestricted;
  394. return shouldUseV4Process;
  395. }
  396. private shouldNormalizeParent(page): boolean {
  397. const Page = mongoose.model('Page') as unknown as PageModel;
  398. return page.grant !== Page.GRANT_RESTRICTED && page.grant !== Page.GRANT_SPECIFIED;
  399. }
  400. /**
  401. * Generate read stream to operate descendants of the specified page path
  402. * @param {string} targetPagePath
  403. * @param {User} viewer
  404. */
  405. private async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  406. const Page = this.crowi.model('Page');
  407. const { PageQueryBuilder } = Page;
  408. const builder = new PageQueryBuilder(Page.find(), true)
  409. .addConditionAsRootOrNotOnTree() // to avoid affecting v5 pages
  410. .addConditionToListOnlyDescendants(targetPagePath);
  411. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  412. return builder
  413. .query
  414. .lean()
  415. .cursor({ batchSize: BULK_REINDEX_SIZE });
  416. }
  417. async renamePage(page: IPage, newPagePath, user, options, activityParameters): Promise<PageDocument | null> {
  418. /*
  419. * Common Operation
  420. */
  421. const Page = mongoose.model('Page') as unknown as PageModel;
  422. const parameters = {
  423. ip: activityParameters.ip,
  424. endpoint: activityParameters.endpoint,
  425. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_RENAME : SupportedAction.ACTION_PAGE_RENAME,
  426. user,
  427. targetModel: 'Page',
  428. target: page,
  429. snapshot: {
  430. username: user.username,
  431. },
  432. };
  433. const activity = await this.crowi.activityService.createActivity(parameters);
  434. const isExist = await Page.exists({ path: newPagePath, isEmpty: false });
  435. if (isExist) {
  436. throw Error(`Page already exists at ${newPagePath}`);
  437. }
  438. if (isTopPage(page.path)) {
  439. throw Error('It is forbidden to rename the top page');
  440. }
  441. // Separate v4 & v5 process
  442. const isShouldUseV4Process = shouldUseV4Process(page);
  443. if (isShouldUseV4Process) {
  444. return this.renamePageV4(page, newPagePath, user, options);
  445. }
  446. if (options.isMoveMode) {
  447. const fromPath = page.path;
  448. const toPath = newPagePath;
  449. const canMove = canMoveByPath(fromPath, toPath) && await Page.exists({ path: newPagePath });
  450. if (!canMove) {
  451. throw Error('Cannot move to this path.');
  452. }
  453. }
  454. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, newPagePath);
  455. if (!canOperate) {
  456. throw Error(`Cannot operate rename to path "${newPagePath}" right now.`);
  457. }
  458. /*
  459. * Resumable Operation
  460. */
  461. let pageOp;
  462. try {
  463. pageOp = await PageOperation.create({
  464. actionType: PageActionType.Rename,
  465. actionStage: PageActionStage.Main,
  466. page,
  467. user,
  468. fromPath: page.path,
  469. toPath: newPagePath,
  470. options,
  471. });
  472. }
  473. catch (err) {
  474. logger.error('Failed to create PageOperation document.', err);
  475. throw err;
  476. }
  477. let renamedPage: PageDocument | null = null;
  478. try {
  479. renamedPage = await this.renameMainOperation(page, newPagePath, user, options, pageOp._id, activity);
  480. }
  481. catch (err) {
  482. logger.error('Error occurred while running renameMainOperation', err);
  483. // cleanup
  484. await PageOperation.deleteOne({ _id: pageOp._id });
  485. throw err;
  486. }
  487. if (page.descendantCount < 1) {
  488. const preNotify = preNotifyService.generatePreNotify(activity);
  489. this.activityEvent.emit('updated', activity, page, preNotify);
  490. }
  491. this.disableAncestorPagesTtl(newPagePath);
  492. return renamedPage;
  493. }
  494. async renameMainOperation(page, newPagePath: string, user, options, pageOpId: ObjectIdLike, activity?): Promise<PageDocument | null> {
  495. const Page = mongoose.model('Page') as unknown as PageModel;
  496. const updateMetadata = options.updateMetadata || false;
  497. // sanitize path
  498. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  499. // UserGroup & Owner validation
  500. // use the parent's grant when target page is an empty page
  501. let grant;
  502. let grantedUserIds;
  503. let grantedGroupIds;
  504. if (page.isEmpty) {
  505. const parent = await Page.findOne({ _id: page.parent });
  506. if (parent == null) {
  507. throw Error('parent not found');
  508. }
  509. grant = parent.grant;
  510. grantedUserIds = parent.grantedUsers;
  511. grantedGroupIds = parent.grantedGroups;
  512. }
  513. else {
  514. grant = page.grant;
  515. grantedUserIds = page.grantedUsers;
  516. grantedGroupIds = page.grantedGroups;
  517. }
  518. if (grant !== Page.GRANT_RESTRICTED) {
  519. let isGrantNormalized = false;
  520. try {
  521. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, newPagePath, grant, grantedUserIds, grantedGroupIds, false);
  522. }
  523. catch (err) {
  524. logger.error(`Failed to validate grant of page at "${newPagePath}" when renaming`, err);
  525. throw err;
  526. }
  527. if (!isGrantNormalized) {
  528. throw Error(`This page cannot be renamed to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  529. }
  530. }
  531. // 1. Take target off from tree
  532. await Page.takeOffFromTree(page._id);
  533. // 2. Find new parent
  534. let newParent;
  535. // If renaming to under target, run getParentAndforceCreateEmptyTree to fill new ancestors
  536. if (this.isRenamingToUnderTarget(page.path, newPagePath)) {
  537. newParent = await this.getParentAndforceCreateEmptyTree(page, newPagePath);
  538. }
  539. else {
  540. newParent = await this.getParentAndFillAncestorsByUser(user, newPagePath);
  541. }
  542. // 3. Put back target page to tree (also update the other attrs)
  543. const update: Partial<IPage> = {};
  544. update.path = newPagePath;
  545. update.parent = newParent._id;
  546. if (updateMetadata) {
  547. update.lastUpdateUser = user;
  548. update.updatedAt = new Date();
  549. }
  550. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  551. // 5.increase parent's descendantCount.
  552. // see: https://dev.growi.org/62149d019311629d4ecd91cf#Handling%20of%20descendantCount%20in%20case%20of%20unexpected%20process%20interruption
  553. const nToIncreaseForOperationInterruption = 1;
  554. await Page.incrementDescendantCountOfPageIds([newParent._id], nToIncreaseForOperationInterruption);
  555. // create page redirect
  556. if (options.createRedirectPage) {
  557. await PageRedirect.create({ fromPath: page.path, toPath: newPagePath });
  558. }
  559. this.pageEvent.emit('rename');
  560. // Set to Sub
  561. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  562. if (pageOp == null) {
  563. throw Error('PageOperation document not found');
  564. }
  565. /*
  566. * Sub Operation
  567. */
  568. this.renameSubOperation(page, newPagePath, user, options, renamedPage, pageOp._id, activity);
  569. return renamedPage;
  570. }
  571. async renameSubOperation(page, newPagePath: string, user, options, renamedPage, pageOpId: ObjectIdLike, activity?): Promise<void> {
  572. const Page = mongoose.model('Page') as unknown as PageModel;
  573. const exParentId = page.parent;
  574. const timerObj = this.crowi.pageOperationService.autoUpdateExpiryDate(pageOpId);
  575. try {
  576. // update descendants first
  577. const descendantsSubscribedSets = new Set();
  578. await this.renameDescendantsWithStream(page, newPagePath, user, options, false, descendantsSubscribedSets);
  579. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  580. const preNotify = preNotifyService.generatePreNotify(activity, () => { return descendantsSubscribedUsers });
  581. this.activityEvent.emit('updated', activity, page, preNotify);
  582. }
  583. catch (err) {
  584. logger.warn(err);
  585. throw Error(err);
  586. }
  587. finally {
  588. this.crowi.pageOperationService.clearAutoUpdateInterval(timerObj);
  589. }
  590. // reduce parent's descendantCount
  591. // see: https://dev.growi.org/62149d019311629d4ecd91cf#Handling%20of%20descendantCount%20in%20case%20of%20unexpected%20process%20interruption
  592. const nToReduceForOperationInterruption = -1;
  593. await Page.incrementDescendantCountOfPageIds([renamedPage.parent], nToReduceForOperationInterruption);
  594. const nToReduce = -1 * ((page.isEmpty ? 0 : 1) + page.descendantCount);
  595. await this.updateDescendantCountOfAncestors(exParentId, nToReduce, true);
  596. // increase ancestore's descendantCount
  597. const nToIncrease = (renamedPage.isEmpty ? 0 : 1) + page.descendantCount;
  598. await this.updateDescendantCountOfAncestors(renamedPage._id, nToIncrease, false);
  599. // Remove leaf empty pages if not moving to under the ex-target position
  600. if (!this.isRenamingToUnderTarget(page.path, newPagePath)) {
  601. // remove empty pages at leaf position
  602. await Page.removeLeafEmptyPagesRecursively(page.parent);
  603. }
  604. await PageOperation.findByIdAndDelete(pageOpId);
  605. }
  606. async resumeRenameSubOperation(renamedPage: PageDocument, pageOp: PageOperationDocument, activity?): Promise<void> {
  607. const isProcessable = pageOp.isProcessable();
  608. if (!isProcessable) {
  609. throw Error('This page operation is currently being processed');
  610. }
  611. if (pageOp.toPath == null) {
  612. throw Error(`Property toPath is missing which is needed to resume rename operation(${pageOp._id})`);
  613. }
  614. const {
  615. page, fromPath, toPath, options, user,
  616. } = pageOp;
  617. this.fixPathsAndDescendantCountOfAncestors(page, user, options, renamedPage, pageOp._id, fromPath, toPath, activity);
  618. }
  619. /**
  620. * Renaming paths and fixing descendantCount of ancestors. It shoud be run synchronously.
  621. * `renameSubOperation` to restart rename operation
  622. * `updateDescendantCountOfPagesWithPaths` to fix descendantCount of ancestors
  623. */
  624. private async fixPathsAndDescendantCountOfAncestors(page, user, options, renamedPage, pageOpId, fromPath, toPath, activity?): Promise<void> {
  625. await this.renameSubOperation(page, toPath, user, options, renamedPage, pageOpId, activity);
  626. const ancestorsPaths = this.crowi.pageOperationService.getAncestorsPathsByFromAndToPath(fromPath, toPath);
  627. await this.updateDescendantCountOfPagesWithPaths(ancestorsPaths);
  628. }
  629. private isRenamingToUnderTarget(fromPath: string, toPath: string): boolean {
  630. const pathToTest = escapeStringRegexp(addTrailingSlash(fromPath));
  631. const pathToBeTested = toPath;
  632. return (new RegExp(`^${pathToTest}`, 'i')).test(pathToBeTested);
  633. }
  634. private async getParentAndforceCreateEmptyTree(originalPage, toPath: string) {
  635. const Page = mongoose.model('Page') as unknown as PageModel;
  636. const fromPath = originalPage.path;
  637. const newParentPath = pathlib.dirname(toPath);
  638. // local util
  639. const collectAncestorPathsUntilFromPath = (path: string, paths: string[] = []): string[] => {
  640. if (path === fromPath) return paths;
  641. const parentPath = pathlib.dirname(path);
  642. paths.push(parentPath);
  643. return collectAncestorPathsUntilFromPath(parentPath, paths);
  644. };
  645. const pathsToInsert = collectAncestorPathsUntilFromPath(toPath);
  646. const originalParent = await Page.findById(originalPage.parent);
  647. if (originalParent == null) {
  648. throw Error('Original parent not found');
  649. }
  650. const insertedPages = await Page.insertMany(pathsToInsert.map((path) => {
  651. return {
  652. path,
  653. isEmpty: true,
  654. };
  655. }));
  656. const pages = [...insertedPages, originalParent];
  657. const ancestorsMap = new Map<string, PageDocument & {_id: any}>(pages.map(p => [p.path, p]));
  658. // bulkWrite to update ancestors
  659. const operations = insertedPages.map((page) => {
  660. const parentPath = pathlib.dirname(page.path);
  661. const op = {
  662. updateOne: {
  663. filter: {
  664. _id: page._id,
  665. },
  666. update: {
  667. $set: {
  668. parent: ancestorsMap.get(parentPath)?._id,
  669. descedantCount: originalParent.descendantCount,
  670. },
  671. },
  672. },
  673. };
  674. return op;
  675. });
  676. await Page.bulkWrite(operations);
  677. const newParent = ancestorsMap.get(newParentPath);
  678. return newParent;
  679. }
  680. private async renamePageV4(page, newPagePath, user, options) {
  681. const Page = this.crowi.model('Page');
  682. const Revision = this.crowi.model('Revision');
  683. const {
  684. isRecursively = false,
  685. createRedirectPage = false,
  686. updateMetadata = false,
  687. } = options;
  688. // sanitize path
  689. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  690. // create descendants first
  691. if (isRecursively) {
  692. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  693. }
  694. const update: any = {};
  695. // update Page
  696. update.path = newPagePath;
  697. if (updateMetadata) {
  698. update.lastUpdateUser = user;
  699. update.updatedAt = Date.now();
  700. }
  701. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  702. // update Rivisions
  703. await Revision.updateRevisionListByPageId(renamedPage._id, { pageId: renamedPage._id });
  704. if (createRedirectPage) {
  705. await PageRedirect.create({ fromPath: page.path, toPath: newPagePath });
  706. }
  707. this.pageEvent.emit('rename');
  708. return renamedPage;
  709. }
  710. private async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  711. // v4 compatible process
  712. if (shouldUseV4Process) {
  713. return this.renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix);
  714. }
  715. const Page = mongoose.model('Page') as unknown as PageModel;
  716. const { updateMetadata, createRedirectPage } = options;
  717. const updatePathOperations: any[] = [];
  718. const insertPageRedirectOperations: any[] = [];
  719. pages.forEach((page) => {
  720. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  721. // increment updatePathOperations
  722. let update;
  723. if (!page.isEmpty && updateMetadata) {
  724. update = {
  725. $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() },
  726. };
  727. }
  728. else {
  729. update = {
  730. $set: { path: newPagePath },
  731. };
  732. }
  733. if (!page.isEmpty && createRedirectPage) {
  734. // insert PageRedirect
  735. insertPageRedirectOperations.push({
  736. insertOne: {
  737. document: {
  738. fromPath: page.path,
  739. toPath: newPagePath,
  740. },
  741. },
  742. });
  743. }
  744. updatePathOperations.push({
  745. updateOne: {
  746. filter: {
  747. _id: page._id,
  748. },
  749. update,
  750. },
  751. });
  752. });
  753. try {
  754. await Page.bulkWrite(updatePathOperations);
  755. }
  756. catch (err) {
  757. if (err.code !== 11000) {
  758. throw new Error(`Failed to rename pages: ${err}`);
  759. }
  760. }
  761. try {
  762. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  763. }
  764. catch (err) {
  765. if (err.code !== 11000) {
  766. throw Error(`Failed to create PageRedirect documents: ${err}`);
  767. }
  768. }
  769. this.pageEvent.emit('updateMany', pages, user);
  770. }
  771. private async renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  772. const pageCollection = mongoose.connection.collection('pages');
  773. const { updateMetadata, createRedirectPage } = options;
  774. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  775. const insertPageRedirectOperations: any[] = [];
  776. pages.forEach((page) => {
  777. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  778. if (updateMetadata) {
  779. unorderedBulkOp
  780. .find({ _id: page._id })
  781. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  782. }
  783. else {
  784. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  785. }
  786. // insert PageRedirect
  787. if (!page.isEmpty && createRedirectPage) {
  788. insertPageRedirectOperations.push({
  789. insertOne: {
  790. document: {
  791. fromPath: page.path,
  792. toPath: newPagePath,
  793. },
  794. },
  795. });
  796. }
  797. });
  798. try {
  799. await unorderedBulkOp.execute();
  800. }
  801. catch (err) {
  802. if (err.code !== 11000) {
  803. throw new Error(`Failed to rename pages: ${err}`);
  804. }
  805. }
  806. try {
  807. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  808. }
  809. catch (err) {
  810. if (err.code !== 11000) {
  811. throw Error(`Failed to create PageRedirect documents: ${err}`);
  812. }
  813. }
  814. this.pageEvent.emit('updateMany', pages, user);
  815. }
  816. private async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?) {
  817. // v4 compatible process
  818. if (shouldUseV4Process) {
  819. return this.renameDescendantsWithStreamV4(targetPage, newPagePath, user, options);
  820. }
  821. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  822. const readStream = await factory.generateReadable();
  823. const newPagePathPrefix = newPagePath;
  824. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  825. const renameDescendants = this.renameDescendants.bind(this);
  826. const pageEvent = this.pageEvent;
  827. let count = 0;
  828. const writeStream = new Writable({
  829. objectMode: true,
  830. async write(batch, encoding, callback) {
  831. try {
  832. count += batch.length;
  833. await renameDescendants(
  834. batch, user, options, pathRegExp, newPagePathPrefix, shouldUseV4Process,
  835. );
  836. const subscribedUsers = await Subscription.getSubscriptions(batch);
  837. subscribedUsers.forEach((eachUser) => {
  838. descendantsSubscribedSets.add(eachUser);
  839. });
  840. logger.debug(`Renaming pages progressing: (count=${count})`);
  841. }
  842. catch (err) {
  843. logger.error('Renaming error on add anyway: ', err);
  844. }
  845. callback();
  846. },
  847. async final(callback) {
  848. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  849. // update path
  850. targetPage.path = newPagePath;
  851. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  852. callback();
  853. },
  854. });
  855. readStream
  856. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  857. .pipe(writeStream);
  858. await streamToPromise(writeStream);
  859. }
  860. private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
  861. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  862. const newPagePathPrefix = newPagePath;
  863. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  864. const renameDescendants = this.renameDescendants.bind(this);
  865. const pageEvent = this.pageEvent;
  866. let count = 0;
  867. const writeStream = new Writable({
  868. objectMode: true,
  869. async write(batch, encoding, callback) {
  870. try {
  871. count += batch.length;
  872. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  873. logger.debug(`Renaming pages progressing: (count=${count})`);
  874. }
  875. catch (err) {
  876. logger.error('renameDescendants error on add anyway: ', err);
  877. }
  878. callback();
  879. },
  880. final(callback) {
  881. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  882. // update path
  883. targetPage.path = newPagePath;
  884. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  885. callback();
  886. },
  887. });
  888. readStream
  889. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  890. .pipe(writeStream);
  891. await streamToPromise(writeStream);
  892. }
  893. /*
  894. * Duplicate
  895. */
  896. async duplicate(page: PageDocument, newPagePath: string, user, isRecursively: boolean, onlyDuplicateUserRelatedResources: boolean) {
  897. /*
  898. * Common Operation
  899. */
  900. const isEmptyAndNotRecursively = page?.isEmpty && !isRecursively;
  901. if (page == null || isEmptyAndNotRecursively) {
  902. throw new Error('Cannot find or duplicate the empty page');
  903. }
  904. const Page = mongoose.model('Page') as unknown as PageModel;
  905. if (!isRecursively && page.isEmpty) {
  906. throw Error('Page not found.');
  907. }
  908. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  909. // 1. Separate v4 & v5 process
  910. const isShouldUseV4Process = shouldUseV4Process(page);
  911. if (isShouldUseV4Process) {
  912. return this.duplicateV4(page, newPagePath, user, isRecursively, onlyDuplicateUserRelatedResources);
  913. }
  914. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPagePath);
  915. if (!canOperate) {
  916. throw Error(`Cannot operate duplicate to path "${newPagePath}" right now.`);
  917. }
  918. // 2. UserGroup & Owner validation
  919. // use the parent's grant when target page is an empty page
  920. let grant: PageGrant;
  921. let grantedUserIds;
  922. let grantedGroupIds: IGrantedGroup[];
  923. if (page.isEmpty) {
  924. const parent = await Page.findOne({ _id: page.parent });
  925. if (parent == null) {
  926. throw Error('parent not found');
  927. }
  928. grant = parent.grant;
  929. grantedUserIds = parent.grantedUsers;
  930. grantedGroupIds = onlyDuplicateUserRelatedResources ? (await this.pageGrantService.getUserRelatedGrantedGroups(parent, user)) : parent.grantedGroups;
  931. }
  932. else {
  933. grant = page.grant;
  934. grantedUserIds = page.grantedUsers;
  935. grantedGroupIds = onlyDuplicateUserRelatedResources ? (await this.pageGrantService.getUserRelatedGrantedGroups(page, user)) : page.grantedGroups;
  936. }
  937. if (grant !== Page.GRANT_RESTRICTED) {
  938. let isGrantNormalized = false;
  939. try {
  940. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, newPagePath, grant, grantedUserIds, grantedGroupIds, false);
  941. }
  942. catch (err) {
  943. logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
  944. throw err;
  945. }
  946. if (!isGrantNormalized) {
  947. throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  948. }
  949. }
  950. // copy & populate (reason why copy: SubOperation only allows non-populated page document)
  951. const copyPage = { ...page };
  952. // 3. Duplicate target
  953. const options: IOptionsForCreate = {
  954. grant,
  955. grantUserGroupIds: grantedGroupIds,
  956. };
  957. let duplicatedTarget;
  958. if (page.isEmpty) {
  959. const parent = await this.getParentAndFillAncestorsByUser(user, newPagePath);
  960. duplicatedTarget = await Page.createEmptyPage(newPagePath, parent);
  961. }
  962. else {
  963. const populatedPage = await page.populate<{revision: IRevisionHasId | null}>({ path: 'revision', model: 'Revision', select: 'body' });
  964. duplicatedTarget = await (this.create as CreateMethod)(
  965. newPagePath, populatedPage?.revision?.body ?? '', user, options,
  966. );
  967. }
  968. this.pageEvent.emit('duplicate', page, user);
  969. // 4. Take over tags
  970. const originTags = await page.findRelatedTagsById();
  971. let savedTags: PageTagRelationDocument[] = [];
  972. if (originTags.length !== 0) {
  973. await PageTagRelation.updatePageTags(duplicatedTarget._id, originTags);
  974. savedTags = await PageTagRelation.listTagNamesByPage(duplicatedTarget._id);
  975. this.tagEvent.emit('update', duplicatedTarget, savedTags);
  976. }
  977. if (isRecursively) {
  978. /*
  979. * Resumable Operation
  980. */
  981. let pageOp;
  982. try {
  983. pageOp = await PageOperation.create({
  984. actionType: PageActionType.Duplicate,
  985. actionStage: PageActionStage.Main,
  986. page: copyPage,
  987. user,
  988. fromPath: page.path,
  989. toPath: newPagePath,
  990. });
  991. }
  992. catch (err) {
  993. logger.error('Failed to create PageOperation document.', err);
  994. throw err;
  995. }
  996. (async() => {
  997. try {
  998. await this.duplicateRecursivelyMainOperation(page, newPagePath, user, pageOp._id, onlyDuplicateUserRelatedResources);
  999. }
  1000. catch (err) {
  1001. logger.error('Error occurred while running duplicateRecursivelyMainOperation.', err);
  1002. // cleanup
  1003. await PageOperation.deleteOne({ _id: pageOp._id });
  1004. throw err;
  1005. }
  1006. })();
  1007. }
  1008. const result = serializePageSecurely(duplicatedTarget);
  1009. result.tags = savedTags;
  1010. return result;
  1011. }
  1012. async duplicateRecursivelyMainOperation(
  1013. page: PageDocument,
  1014. newPagePath: string,
  1015. user,
  1016. pageOpId: ObjectIdLike,
  1017. onlyDuplicateUserRelatedResources: boolean,
  1018. ): Promise<void> {
  1019. const nDuplicatedPages = await this.duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources, false);
  1020. // normalize parent of descendant pages
  1021. const shouldNormalize = this.shouldNormalizeParent(page);
  1022. if (shouldNormalize) {
  1023. try {
  1024. await this.normalizeParentAndDescendantCountOfDescendants(newPagePath, user, true);
  1025. logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
  1026. }
  1027. catch (err) {
  1028. logger.error('Failed to normalize descendants afrer duplicate:', err);
  1029. throw err;
  1030. }
  1031. }
  1032. // Set to Sub
  1033. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1034. if (pageOp == null) {
  1035. throw Error('PageOperation document not found');
  1036. }
  1037. /*
  1038. * Sub Operation
  1039. */
  1040. await this.duplicateRecursivelySubOperation(newPagePath, nDuplicatedPages, pageOp._id);
  1041. }
  1042. async duplicateRecursivelySubOperation(newPagePath: string, nDuplicatedPages: number, pageOpId: ObjectIdLike): Promise<void> {
  1043. const Page = mongoose.model('Page');
  1044. const newTarget = await Page.findOne({ path: newPagePath }); // only one page will be found since duplicating to existing path is forbidden
  1045. if (newTarget == null) {
  1046. throw Error('No duplicated page found. Something might have gone wrong in duplicateRecursivelyMainOperation.');
  1047. }
  1048. await this.updateDescendantCountOfAncestors(newTarget._id, nDuplicatedPages, false);
  1049. await PageOperation.findByIdAndDelete(pageOpId);
  1050. }
  1051. async duplicateV4(page, newPagePath, user, isRecursively, onlyDuplicateUserRelatedResources: boolean) {
  1052. // populate
  1053. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  1054. // create option
  1055. const options: any = { page };
  1056. options.grant = page.grant;
  1057. options.grantUserGroupIds = page.grantedGroups;
  1058. options.grantedUserIds = page.grantedUsers;
  1059. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  1060. const createdPage = await this.create(
  1061. newPagePath, page.revision.body, user, options,
  1062. );
  1063. this.pageEvent.emit('duplicate', page, user);
  1064. if (isRecursively) {
  1065. this.duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources);
  1066. }
  1067. // take over tags
  1068. const originTags = await page.findRelatedTagsById();
  1069. let savedTags: PageTagRelationDocument[] = [];
  1070. if (originTags != null) {
  1071. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  1072. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  1073. this.tagEvent.emit('update', createdPage, savedTags);
  1074. }
  1075. const result = serializePageSecurely(createdPage);
  1076. result.tags = savedTags;
  1077. return result;
  1078. }
  1079. /**
  1080. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  1081. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  1082. */
  1083. private async duplicateTags(pageIdMapping) {
  1084. // convert pageId from string to ObjectId
  1085. const pageIds = Object.keys(pageIdMapping);
  1086. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  1087. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  1088. {
  1089. $match: stage,
  1090. },
  1091. {
  1092. $group: {
  1093. _id: '$relatedTag',
  1094. relatedPages: { $push: '$relatedPage' },
  1095. },
  1096. },
  1097. ]);
  1098. const newPageTagRelation: any[] = [];
  1099. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  1100. // relatedPages
  1101. relatedPages.forEach((pageId) => {
  1102. newPageTagRelation.push({
  1103. relatedPage: pageIdMapping[pageId], // newPageId
  1104. relatedTag: _id,
  1105. });
  1106. });
  1107. });
  1108. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  1109. }
  1110. private async duplicateDescendants(
  1111. pages, user, oldPagePathPrefix, newPagePathPrefix,
  1112. onlyDuplicateUserRelatedResources: boolean, shouldUseV4Process = true,
  1113. ) {
  1114. if (shouldUseV4Process) {
  1115. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  1116. }
  1117. const Page = this.crowi.model('Page');
  1118. const Revision = this.crowi.model('Revision');
  1119. const pageIds = pages.map(page => page._id);
  1120. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  1121. // Mapping to set to the body of the new revision
  1122. const pageIdRevisionMapping = {};
  1123. revisions.forEach((revision) => {
  1124. pageIdRevisionMapping[revision.pageId] = revision;
  1125. });
  1126. // key: oldPageId, value: newPageId
  1127. const pageIdMapping = {};
  1128. const newPages: any[] = [];
  1129. const newRevisions: any[] = [];
  1130. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  1131. // no need to save parent here
  1132. pages.forEach((page) => {
  1133. const newPageId = new mongoose.Types.ObjectId();
  1134. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1135. const revisionId = new mongoose.Types.ObjectId();
  1136. pageIdMapping[page._id] = newPageId;
  1137. const isDuplicateTarget = !page.isEmpty
  1138. && (!onlyDuplicateUserRelatedResources || this.pageGrantService.isUserGrantedPageAccess(page, user, userRelatedGroups));
  1139. if (isDuplicateTarget) {
  1140. const grantedGroups = onlyDuplicateUserRelatedResources
  1141. ? this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(userRelatedGroups, page)
  1142. : page.grantedGroups;
  1143. const newPage = {
  1144. _id: newPageId,
  1145. path: newPagePath,
  1146. creator: user._id,
  1147. grant: page.grant,
  1148. grantedGroups,
  1149. grantedUsers: page.grantedUsers,
  1150. lastUpdateUser: user._id,
  1151. revision: revisionId,
  1152. };
  1153. newRevisions.push({
  1154. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  1155. });
  1156. newPages.push(newPage);
  1157. }
  1158. });
  1159. await Page.insertMany(newPages, { ordered: false });
  1160. await Revision.insertMany(newRevisions, { ordered: false });
  1161. await this.duplicateTags(pageIdMapping);
  1162. }
  1163. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  1164. const Page = this.crowi.model('Page');
  1165. const Revision = this.crowi.model('Revision');
  1166. const pageIds = pages.map(page => page._id);
  1167. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  1168. // Mapping to set to the body of the new revision
  1169. const pageIdRevisionMapping = {};
  1170. revisions.forEach((revision) => {
  1171. pageIdRevisionMapping[revision.pageId] = revision;
  1172. });
  1173. // key: oldPageId, value: newPageId
  1174. const pageIdMapping = {};
  1175. const newPages: any[] = [];
  1176. const newRevisions: any[] = [];
  1177. pages.forEach((page) => {
  1178. const newPageId = new mongoose.Types.ObjectId();
  1179. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1180. const revisionId = new mongoose.Types.ObjectId();
  1181. pageIdMapping[page._id] = newPageId;
  1182. newPages.push({
  1183. _id: newPageId,
  1184. path: newPagePath,
  1185. creator: user._id,
  1186. grant: page.grant,
  1187. grantedGroups: page.grantedGroups,
  1188. grantedUsers: page.grantedUsers,
  1189. lastUpdateUser: user._id,
  1190. revision: revisionId,
  1191. });
  1192. newRevisions.push({
  1193. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  1194. });
  1195. });
  1196. await Page.insertMany(newPages, { ordered: false });
  1197. await Revision.insertMany(newRevisions, { ordered: false });
  1198. await this.duplicateTags(pageIdMapping);
  1199. }
  1200. private async duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources: boolean, shouldUseV4Process = true) {
  1201. if (shouldUseV4Process) {
  1202. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user, onlyDuplicateUserRelatedResources);
  1203. }
  1204. const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
  1205. const readStream = await iterableFactory.generateReadable();
  1206. const newPagePathPrefix = newPagePath;
  1207. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1208. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1209. const pageEvent = this.pageEvent;
  1210. let count = 0;
  1211. let nNonEmptyDuplicatedPages = 0;
  1212. const writeStream = new Writable({
  1213. objectMode: true,
  1214. async write(batch, encoding, callback) {
  1215. try {
  1216. count += batch.length;
  1217. nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
  1218. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, onlyDuplicateUserRelatedResources, shouldUseV4Process);
  1219. logger.debug(`Adding pages progressing: (count=${count})`);
  1220. }
  1221. catch (err) {
  1222. logger.error('addAllPages error on add anyway: ', err);
  1223. }
  1224. callback();
  1225. },
  1226. async final(callback) {
  1227. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1228. // update path
  1229. page.path = newPagePath;
  1230. pageEvent.emit('syncDescendantsUpdate', page, user);
  1231. callback();
  1232. },
  1233. });
  1234. readStream
  1235. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1236. .pipe(writeStream);
  1237. await streamToPromise(writeStream);
  1238. return nNonEmptyDuplicatedPages;
  1239. }
  1240. private async duplicateDescendantsWithStreamV4(page, newPagePath, user, onlyDuplicateUserRelatedResources: boolean) {
  1241. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  1242. const newPagePathPrefix = newPagePath;
  1243. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1244. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1245. const pageEvent = this.pageEvent;
  1246. let count = 0;
  1247. const writeStream = new Writable({
  1248. objectMode: true,
  1249. async write(batch, encoding, callback) {
  1250. try {
  1251. count += batch.length;
  1252. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, onlyDuplicateUserRelatedResources);
  1253. logger.debug(`Adding pages progressing: (count=${count})`);
  1254. }
  1255. catch (err) {
  1256. logger.error('addAllPages error on add anyway: ', err);
  1257. }
  1258. callback();
  1259. },
  1260. final(callback) {
  1261. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1262. // update path
  1263. page.path = newPagePath;
  1264. pageEvent.emit('syncDescendantsUpdate', page, user);
  1265. callback();
  1266. },
  1267. });
  1268. readStream
  1269. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1270. .pipe(writeStream);
  1271. await streamToPromise(writeStream);
  1272. return count;
  1273. }
  1274. /*
  1275. * Delete
  1276. */
  1277. async deletePage(page, user, options = {}, isRecursively = false, activityParameters) {
  1278. /*
  1279. * Common Operation
  1280. */
  1281. const Page = mongoose.model('Page') as PageModel;
  1282. // Separate v4 & v5 process
  1283. const isShouldUseV4Process = shouldUseV4Process(page);
  1284. if (isShouldUseV4Process) {
  1285. return this.deletePageV4(page, user, options, isRecursively);
  1286. }
  1287. // Validate
  1288. if (page.isEmpty && !isRecursively) {
  1289. throw Error('Page not found.');
  1290. }
  1291. const isTrashed = isTrashPage(page.path);
  1292. if (isTrashed) {
  1293. throw new Error('This method does NOT support deleting trashed pages.');
  1294. }
  1295. if (isTopPage(page.path) || isUsersTopPage(page.path)) {
  1296. throw new Error('Page is not deletable.');
  1297. }
  1298. if (pagePathUtils.isUsersHomepage(page.path)) {
  1299. if (!this.canDeleteUserHomepageByConfig()) {
  1300. throw new Error('User Homepage is not deletable.');
  1301. }
  1302. if (!await this.isUsersHomepageOwnerAbsent(page.path)) {
  1303. throw new Error('User Homepage is not deletable.');
  1304. }
  1305. }
  1306. const newPath = Page.getDeletedPageName(page.path);
  1307. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1308. if (!canOperate) {
  1309. throw Error(`Cannot operate delete to path "${newPath}" right now.`);
  1310. }
  1311. // Replace with an empty page
  1312. const isChildrenExist = await Page.exists({ parent: page._id });
  1313. const shouldReplace = !isRecursively && isChildrenExist;
  1314. if (shouldReplace) {
  1315. await Page.replaceTargetWithPage(page, null, true);
  1316. }
  1317. const parameters = {
  1318. ip: activityParameters.ip,
  1319. endpoint: activityParameters.endpoint,
  1320. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE : SupportedAction.ACTION_PAGE_DELETE,
  1321. user,
  1322. target: page,
  1323. targetModel: 'Page',
  1324. snapshot: {
  1325. username: user.username,
  1326. },
  1327. };
  1328. const activity = await this.crowi.activityService.createActivity(parameters);
  1329. // Delete target (only updating an existing document's properties )
  1330. let deletedPage;
  1331. if (!page.isEmpty) {
  1332. deletedPage = await this.deleteNonEmptyTarget(page, user);
  1333. }
  1334. else { // always recursive
  1335. deletedPage = page;
  1336. await Page.deleteOne({ _id: page._id, isEmpty: true });
  1337. }
  1338. // 1. Update descendantCount
  1339. if (isRecursively) {
  1340. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1341. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1342. }
  1343. else {
  1344. // update descendantCount of ancestors'
  1345. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  1346. }
  1347. // 2. Delete leaf empty pages
  1348. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1349. if (isRecursively) {
  1350. let pageOp;
  1351. try {
  1352. pageOp = await PageOperation.create({
  1353. actionType: PageActionType.Delete,
  1354. actionStage: PageActionStage.Main,
  1355. page,
  1356. user,
  1357. fromPath: page.path,
  1358. toPath: newPath,
  1359. });
  1360. }
  1361. catch (err) {
  1362. logger.error('Failed to create PageOperation document.', err);
  1363. throw err;
  1364. }
  1365. /*
  1366. * Resumable Operation
  1367. */
  1368. (async() => {
  1369. try {
  1370. await this.deleteRecursivelyMainOperation(page, user, pageOp._id, activity);
  1371. }
  1372. catch (err) {
  1373. logger.error('Error occurred while running deleteRecursivelyMainOperation.', err);
  1374. // cleanup
  1375. await PageOperation.deleteOne({ _id: pageOp._id });
  1376. throw err;
  1377. }
  1378. finally {
  1379. this.pageEvent.emit('syncDescendantsUpdate', deletedPage, user);
  1380. }
  1381. })();
  1382. }
  1383. else {
  1384. const preNotify = preNotifyService.generatePreNotify(activity);
  1385. this.activityEvent.emit('updated', activity, page, preNotify);
  1386. }
  1387. return deletedPage;
  1388. }
  1389. private async deleteNonEmptyTarget(page, user) {
  1390. const Page = mongoose.model('Page') as unknown as PageModel;
  1391. const newPath = Page.getDeletedPageName(page.path);
  1392. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1393. $set: {
  1394. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1395. },
  1396. }, { new: true });
  1397. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1398. try {
  1399. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1400. }
  1401. catch (err) {
  1402. if (err.code !== 11000) {
  1403. throw err;
  1404. }
  1405. }
  1406. this.pageEvent.emit('delete', page, deletedPage, user);
  1407. return deletedPage;
  1408. }
  1409. async deleteRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1410. const descendantsSubscribedSets = new Set();
  1411. await this.deleteDescendantsWithStream(page, user, false, descendantsSubscribedSets);
  1412. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1413. const preNotify = preNotifyService.generatePreNotify(activity, () => { return descendantsSubscribedUsers });
  1414. this.activityEvent.emit('updated', activity, page, preNotify);
  1415. await PageOperation.findByIdAndDelete(pageOpId);
  1416. // no sub operation available
  1417. }
  1418. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  1419. const Page = mongoose.model('Page') as PageModel;
  1420. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  1421. const newPath = Page.getDeletedPageName(page.path);
  1422. const isTrashed = isTrashPage(page.path);
  1423. if (isTrashed) {
  1424. throw new Error('This method does NOT support deleting trashed pages.');
  1425. }
  1426. if (!isMovablePage(page.path)) {
  1427. throw new Error('Page is not deletable.');
  1428. }
  1429. if (isRecursively) {
  1430. this.deleteDescendantsWithStream(page, user);
  1431. }
  1432. // update Revisions
  1433. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  1434. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1435. $set: {
  1436. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  1437. },
  1438. }, { new: true });
  1439. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1440. try {
  1441. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1442. }
  1443. catch (err) {
  1444. if (err.code !== 11000) {
  1445. throw err;
  1446. }
  1447. }
  1448. this.pageEvent.emit('delete', page, deletedPage, user);
  1449. return deletedPage;
  1450. }
  1451. private async deleteDescendants(pages, user) {
  1452. const Page = mongoose.model('Page') as unknown as PageModel;
  1453. const deletePageOperations: any[] = [];
  1454. const insertPageRedirectOperations: any[] = [];
  1455. pages.forEach((page) => {
  1456. const newPath = Page.getDeletedPageName(page.path);
  1457. let operation;
  1458. // if empty, delete completely
  1459. if (page.isEmpty) {
  1460. operation = {
  1461. deleteOne: {
  1462. filter: { _id: page._id },
  1463. },
  1464. };
  1465. }
  1466. // if not empty, set parent to null and update to trash
  1467. else {
  1468. operation = {
  1469. updateOne: {
  1470. filter: { _id: page._id },
  1471. update: {
  1472. $set: {
  1473. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1474. },
  1475. },
  1476. },
  1477. };
  1478. insertPageRedirectOperations.push({
  1479. insertOne: {
  1480. document: {
  1481. fromPath: page.path,
  1482. toPath: newPath,
  1483. },
  1484. },
  1485. });
  1486. }
  1487. deletePageOperations.push(operation);
  1488. });
  1489. try {
  1490. await Page.bulkWrite(deletePageOperations);
  1491. }
  1492. catch (err) {
  1493. if (err.code !== 11000) {
  1494. throw new Error(`Failed to delete pages: ${err}`);
  1495. }
  1496. }
  1497. finally {
  1498. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  1499. }
  1500. try {
  1501. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  1502. }
  1503. catch (err) {
  1504. if (err.code !== 11000) {
  1505. throw Error(`Failed to create PageRedirect documents: ${err}`);
  1506. }
  1507. }
  1508. }
  1509. /**
  1510. * Create delete stream and return deleted document count
  1511. */
  1512. private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1513. let readStream;
  1514. if (shouldUseV4Process) {
  1515. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1516. }
  1517. else {
  1518. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1519. readStream = await factory.generateReadable();
  1520. }
  1521. const deleteDescendants = this.deleteDescendants.bind(this);
  1522. let count = 0;
  1523. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1524. const writeStream = new Writable({
  1525. objectMode: true,
  1526. async write(batch, encoding, callback) {
  1527. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1528. try {
  1529. count += batch.length;
  1530. await deleteDescendants(batch, user);
  1531. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1532. subscribedUsers.forEach((eachUser) => {
  1533. descendantsSubscribedSets.add(eachUser);
  1534. });
  1535. logger.debug(`Deleting pages progressing: (count=${count})`);
  1536. }
  1537. catch (err) {
  1538. logger.error('deleteDescendants error on add anyway: ', err);
  1539. }
  1540. callback();
  1541. },
  1542. final(callback) {
  1543. logger.debug(`Deleting pages has completed: (totalCount=${count})`);
  1544. callback();
  1545. },
  1546. });
  1547. readStream
  1548. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1549. .pipe(writeStream);
  1550. await streamToPromise(writeStream);
  1551. return nDeletedNonEmptyPages;
  1552. }
  1553. async deleteCompletelyOperation(pageIds, pagePaths): Promise<void> {
  1554. // Delete Attachments, Revisions, Pages and emit delete
  1555. const Page = this.crowi.model('Page');
  1556. const Revision = this.crowi.model('Revision');
  1557. const { attachmentService } = this.crowi;
  1558. const attachments = await Attachment.find({ page: { $in: pageIds } });
  1559. await Promise.all([
  1560. Comment.deleteMany({ page: { $in: pageIds } }),
  1561. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  1562. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  1563. Revision.deleteMany({ pageId: { $in: pageIds } }),
  1564. Page.deleteMany({ _id: { $in: pageIds } }),
  1565. PageRedirect.deleteMany({ $or: [{ fromPath: { $in: pagePaths } }, { toPath: { $in: pagePaths } }] }),
  1566. attachmentService.removeAllAttachments(attachments),
  1567. // Leave bookmarks without deleting -- 2024.05.17 Yuki Takei
  1568. ]);
  1569. }
  1570. // delete multiple pages
  1571. async deleteMultipleCompletely(pages, user) {
  1572. const ids = pages.map(page => (page._id));
  1573. const paths = pages.map(page => (page.path));
  1574. logger.debug('Deleting completely', paths);
  1575. await this.deleteCompletelyOperation(ids, paths);
  1576. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  1577. return;
  1578. }
  1579. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false, activityParameters) {
  1580. /*
  1581. * Common Operation
  1582. */
  1583. const Page = mongoose.model('Page') as PageModel;
  1584. if (isTopPage(page.path)) {
  1585. throw Error('It is forbidden to delete the top page');
  1586. }
  1587. if (page.isEmpty && !isRecursively) {
  1588. throw Error('Page not found.');
  1589. }
  1590. // v4 compatible process
  1591. const isShouldUseV4Process = shouldUseV4Process(page);
  1592. if (isShouldUseV4Process) {
  1593. return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
  1594. }
  1595. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, null);
  1596. if (!canOperate) {
  1597. throw Error(`Cannot operate deleteCompletely from path "${page.path}" right now.`);
  1598. }
  1599. const ids = [page._id];
  1600. const paths = [page.path];
  1601. logger.debug('Deleting completely', paths);
  1602. const parameters = {
  1603. ip: activityParameters.ip,
  1604. endpoint: activityParameters.endpoint,
  1605. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE_COMPLETELY : SupportedAction.ACTION_PAGE_DELETE_COMPLETELY,
  1606. user,
  1607. target: page,
  1608. targetModel: 'Page',
  1609. snapshot: {
  1610. username: user.username,
  1611. },
  1612. };
  1613. const activity = await this.crowi.activityService.createActivity(parameters);
  1614. // 1. update descendantCount
  1615. if (isRecursively) {
  1616. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1617. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1618. }
  1619. else {
  1620. // replace with an empty page
  1621. const shouldReplace = await Page.exists({ parent: page._id });
  1622. let pageToUpdateDescendantCount = page;
  1623. if (shouldReplace) {
  1624. pageToUpdateDescendantCount = await Page.replaceTargetWithPage(page);
  1625. }
  1626. await this.updateDescendantCountOfAncestors(pageToUpdateDescendantCount.parent, -1, true);
  1627. }
  1628. // 2. then delete target completely
  1629. await this.deleteCompletelyOperation(ids, paths);
  1630. // delete leaf empty pages
  1631. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1632. if (!page.isEmpty && !preventEmitting) {
  1633. this.pageEvent.emit('deleteCompletely', page, user);
  1634. }
  1635. if (isRecursively) {
  1636. let pageOp;
  1637. try {
  1638. pageOp = await PageOperation.create({
  1639. actionType: PageActionType.DeleteCompletely,
  1640. actionStage: PageActionStage.Main,
  1641. page,
  1642. user,
  1643. fromPath: page.path,
  1644. options,
  1645. });
  1646. }
  1647. catch (err) {
  1648. logger.error('Failed to create PageOperation document.', err);
  1649. throw err;
  1650. }
  1651. /*
  1652. * Main Operation
  1653. */
  1654. (async() => {
  1655. try {
  1656. await this.deleteCompletelyRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1657. }
  1658. catch (err) {
  1659. logger.error('Error occurred while running deleteCompletelyRecursivelyMainOperation.', err);
  1660. // cleanup
  1661. await PageOperation.deleteOne({ _id: pageOp._id });
  1662. throw err;
  1663. }
  1664. })();
  1665. }
  1666. else {
  1667. const preNotify = preNotifyService.generatePreNotify(activity);
  1668. this.activityEvent.emit('updated', activity, page, preNotify);
  1669. }
  1670. return;
  1671. }
  1672. async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1673. const descendantsSubscribedSets = new Set();
  1674. await this.deleteCompletelyDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1675. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1676. const preNotify = preNotifyService.generatePreNotify(activity, () => { return descendantsSubscribedUsers });
  1677. this.activityEvent.emit('updated', activity, page, preNotify);
  1678. await PageOperation.findByIdAndDelete(pageOpId);
  1679. // no sub operation available
  1680. }
  1681. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1682. const ids = [page._id];
  1683. const paths = [page.path];
  1684. logger.debug('Deleting completely', paths);
  1685. await this.deleteCompletelyOperation(ids, paths);
  1686. if (isRecursively) {
  1687. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1688. }
  1689. if (!page.isEmpty && !preventEmitting) {
  1690. this.pageEvent.emit('deleteCompletely', page, user);
  1691. }
  1692. return;
  1693. }
  1694. async emptyTrashPage(user, options = {}, activityParameters) {
  1695. const page = { path: '/trash' };
  1696. const parameters = {
  1697. ...activityParameters,
  1698. action: SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE_COMPLETELY,
  1699. user,
  1700. targetModel: 'Page',
  1701. snapshot: {
  1702. username: user.username,
  1703. },
  1704. };
  1705. const activity = await this.crowi.activityService.createActivity(parameters);
  1706. const descendantsSubscribedSets = new Set();
  1707. const pages = await this.deleteCompletelyDescendantsWithStream(page, user, options, true, descendantsSubscribedSets);
  1708. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1709. const preNotify = preNotifyService.generatePreNotify(activity, () => { return descendantsSubscribedUsers });
  1710. this.activityEvent.emit('updated', activity, page, preNotify);
  1711. return pages;
  1712. }
  1713. /**
  1714. * Create delete completely stream
  1715. */
  1716. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1717. let readStream;
  1718. if (shouldUseV4Process) { // pages don't have parents
  1719. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1720. }
  1721. else {
  1722. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1723. readStream = await factory.generateReadable();
  1724. }
  1725. let count = 0;
  1726. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1727. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1728. const writeStream = new Writable({
  1729. objectMode: true,
  1730. async write(batch, encoding, callback) {
  1731. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1732. try {
  1733. count += batch.length;
  1734. await deleteMultipleCompletely(batch, user);
  1735. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1736. subscribedUsers.forEach((eachUser) => {
  1737. descendantsSubscribedSets.add(eachUser);
  1738. });
  1739. logger.debug(`Adding pages progressing: (count=${count})`);
  1740. }
  1741. catch (err) {
  1742. logger.error('addAllPages error on add anyway: ', err);
  1743. }
  1744. callback();
  1745. },
  1746. final(callback) {
  1747. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1748. callback();
  1749. },
  1750. });
  1751. readStream
  1752. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1753. .pipe(writeStream);
  1754. await streamToPromise(writeStream);
  1755. return nDeletedNonEmptyPages;
  1756. }
  1757. // no need to separate Main Sub since it is devided into single page operations
  1758. async deleteMultiplePages(pagesToDelete, user, options, activityParameters): Promise<void> {
  1759. const { isRecursively, isCompletely } = options;
  1760. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1761. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1762. }
  1763. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1764. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1765. if (isCompletely) {
  1766. for await (const page of pages) {
  1767. await this.deleteCompletely(page, user, {}, isRecursively, false, activityParameters);
  1768. }
  1769. }
  1770. else {
  1771. for await (const page of pages) {
  1772. await this.deletePage(page, user, {}, isRecursively, activityParameters);
  1773. }
  1774. }
  1775. }
  1776. // use the same process in both v4 and v5
  1777. private async revertDeletedDescendants(pages, user) {
  1778. const Page = this.crowi.model('Page');
  1779. const revertPageOperations: any[] = [];
  1780. const fromPathsToDelete: string[] = [];
  1781. pages.forEach((page) => {
  1782. // e.g. page.path = /trash/test, toPath = /test
  1783. const toPath = Page.getRevertDeletedPageName(page.path);
  1784. revertPageOperations.push({
  1785. updateOne: {
  1786. filter: { _id: page._id },
  1787. update: {
  1788. $set: {
  1789. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1790. },
  1791. },
  1792. },
  1793. });
  1794. fromPathsToDelete.push(page.path);
  1795. });
  1796. try {
  1797. await Page.bulkWrite(revertPageOperations);
  1798. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1799. }
  1800. catch (err) {
  1801. if (err.code !== 11000) {
  1802. throw new Error(`Failed to revert pages: ${err}`);
  1803. }
  1804. }
  1805. }
  1806. async revertDeletedPage(page, user, options = {}, isRecursively = false, activityParameters?) {
  1807. /*
  1808. * Common Operation
  1809. */
  1810. const Page = this.crowi.model('Page');
  1811. const parameters = {
  1812. ip: activityParameters.ip,
  1813. endpoint: activityParameters.endpoint,
  1814. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_REVERT : SupportedAction.ACTION_PAGE_REVERT,
  1815. user,
  1816. target: page,
  1817. targetModel: 'Page',
  1818. snapshot: {
  1819. username: user.username,
  1820. },
  1821. };
  1822. const activity = await this.crowi.activityService.createActivity(parameters);
  1823. // 1. Separate v4 & v5 process
  1824. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1825. if (shouldUseV4Process) {
  1826. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1827. }
  1828. const newPath = Page.getRevertDeletedPageName(page.path);
  1829. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1830. if (!canOperate) {
  1831. throw Error(`Cannot operate revert from path "${page.path}" right now.`);
  1832. }
  1833. const includeEmpty = true;
  1834. const originPage = await Page.findByPath(newPath, includeEmpty);
  1835. // throw if any page already exists when recursively operation
  1836. if (originPage != null && (!originPage.isEmpty || isRecursively)) {
  1837. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1838. }
  1839. // 2. Revert target
  1840. const parent = await this.getParentAndFillAncestorsByUser(user, newPath);
  1841. const shouldReplace = originPage != null && originPage.isEmpty;
  1842. let updatedPage = await Page.findByIdAndUpdate(page._id, {
  1843. $set: {
  1844. path: newPath,
  1845. status: Page.STATUS_PUBLISHED,
  1846. lastUpdateUser: user._id,
  1847. deleteUser: null,
  1848. deletedAt: null,
  1849. parent: parent._id,
  1850. descendantCount: shouldReplace ? originPage.descendantCount : 0,
  1851. },
  1852. }, { new: true });
  1853. if (shouldReplace) {
  1854. updatedPage = await Page.replaceTargetWithPage(originPage, updatedPage, true);
  1855. }
  1856. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1857. this.pageEvent.emit('revert', page, updatedPage, user);
  1858. if (!isRecursively) {
  1859. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1860. const preNotify = preNotifyService.generatePreNotify(activity);
  1861. this.activityEvent.emit('updated', activity, page, preNotify);
  1862. }
  1863. else {
  1864. let pageOp;
  1865. try {
  1866. pageOp = await PageOperation.create({
  1867. actionType: PageActionType.Revert,
  1868. actionStage: PageActionStage.Main,
  1869. page,
  1870. user,
  1871. fromPath: page.path,
  1872. toPath: newPath,
  1873. options,
  1874. });
  1875. }
  1876. catch (err) {
  1877. logger.error('Failed to create PageOperation document.', err);
  1878. throw err;
  1879. }
  1880. /*
  1881. * Resumable Operation
  1882. */
  1883. (async() => {
  1884. try {
  1885. await this.revertRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1886. this.pageEvent.emit('syncDescendantsUpdate', updatedPage, user);
  1887. }
  1888. catch (err) {
  1889. logger.error('Error occurred while running revertRecursivelyMainOperation.', err);
  1890. // cleanup
  1891. await PageOperation.deleteOne({ _id: pageOp._id });
  1892. throw err;
  1893. }
  1894. })();
  1895. }
  1896. return updatedPage;
  1897. }
  1898. async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1899. const Page = mongoose.model('Page') as unknown as PageModel;
  1900. const descendantsSubscribedSets = new Set();
  1901. await this.revertDeletedDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1902. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1903. const preNotify = preNotifyService.generatePreNotify(activity, () => { return descendantsSubscribedUsers });
  1904. this.activityEvent.emit('updated', activity, page, preNotify);
  1905. const newPath = Page.getRevertDeletedPageName(page.path);
  1906. // normalize parent of descendant pages
  1907. const shouldNormalize = this.shouldNormalizeParent(page);
  1908. if (shouldNormalize) {
  1909. try {
  1910. await this.normalizeParentAndDescendantCountOfDescendants(newPath, user);
  1911. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1912. }
  1913. catch (err) {
  1914. logger.error('Failed to normalize descendants afrer revert:', err);
  1915. throw err;
  1916. }
  1917. }
  1918. // Set to Sub
  1919. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1920. if (pageOp == null) {
  1921. throw Error('PageOperation document not found');
  1922. }
  1923. /*
  1924. * Sub Operation
  1925. */
  1926. await this.revertRecursivelySubOperation(newPath, pageOp._id);
  1927. }
  1928. async revertRecursivelySubOperation(newPath: string, pageOpId: ObjectIdLike): Promise<void> {
  1929. const Page = mongoose.model('Page') as unknown as PageModel;
  1930. const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
  1931. if (newTarget == null) {
  1932. throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
  1933. }
  1934. // update descendantCount of ancestors'
  1935. await this.updateDescendantCountOfAncestors(newTarget.parent as ObjectIdLike, newTarget.descendantCount + 1, true);
  1936. await PageOperation.findByIdAndDelete(pageOpId);
  1937. }
  1938. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1939. const Page = this.crowi.model('Page');
  1940. const newPath = Page.getRevertDeletedPageName(page.path);
  1941. const originPage = await Page.findByPath(newPath);
  1942. if (originPage != null) {
  1943. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1944. }
  1945. if (isRecursively) {
  1946. this.revertDeletedDescendantsWithStream(page, user, options);
  1947. }
  1948. page.status = Page.STATUS_PUBLISHED;
  1949. page.lastUpdateUser = user;
  1950. debug('Revert deleted the page', page, newPath);
  1951. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1952. $set: {
  1953. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1954. },
  1955. }, { new: true });
  1956. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1957. this.pageEvent.emit('revert', page, updatedPage, user);
  1958. return updatedPage;
  1959. }
  1960. private async applyScopesToDescendantsWithStream(parentPage, user, isV4 = false) {
  1961. const Page = this.crowi.model('Page');
  1962. const builder = new Page.PageQueryBuilder(Page.find());
  1963. builder.addConditionToListOnlyDescendants(parentPage.path);
  1964. if (isV4) {
  1965. builder.addConditionAsRootOrNotOnTree();
  1966. }
  1967. else {
  1968. builder.addConditionAsOnTree();
  1969. }
  1970. // add grant conditions
  1971. await Page.addConditionToFilteringByViewerToEdit(builder, user);
  1972. const grant = parentPage.grant;
  1973. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  1974. const userRelatedParentGrantedGroups = this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(
  1975. userRelatedGroups, parentPage,
  1976. );
  1977. const childPagesReadableStream = builder.query.cursor({ batchSize: BULK_REINDEX_SIZE });
  1978. const childPagesWritable = new Writable({
  1979. objectMode: true,
  1980. write: async(batch, encoding, callback) => {
  1981. await this.updateChildPagesGrant(batch, grant, user, userRelatedGroups, userRelatedParentGrantedGroups);
  1982. callback();
  1983. },
  1984. });
  1985. childPagesReadableStream
  1986. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1987. .pipe(childPagesWritable);
  1988. await streamToPromise(childPagesWritable);
  1989. }
  1990. async updateChildPagesGrant(
  1991. pages: PageDocument[], grant: PageGrant, user, userRelatedGroups: PopulatedGrantedGroup[], userRelatedParentGrantedGroups: IGrantedGroup[],
  1992. ): Promise<void> {
  1993. const Page = this.crowi.model('Page');
  1994. const operations: any = [];
  1995. pages.forEach((childPage) => {
  1996. let newChildGrantedGroups: IGrantedGroup[] = [];
  1997. if (grant === PageGrant.GRANT_USER_GROUP) {
  1998. newChildGrantedGroups = this.getNewGrantedGroupsSyncronously(userRelatedGroups, userRelatedParentGrantedGroups, childPage);
  1999. }
  2000. const canChangeGrant = this.pageGrantService
  2001. .validateGrantChangeSyncronously(userRelatedGroups, childPage.grantedGroups, grant, newChildGrantedGroups);
  2002. if (canChangeGrant) {
  2003. operations.push({
  2004. updateOne: {
  2005. filter: { _id: childPage._id },
  2006. update: { $set: { grant, grantedUsers: grant === PageGrant.GRANT_OWNER ? [user._id] : [], grantedGroups: newChildGrantedGroups } },
  2007. },
  2008. });
  2009. }
  2010. });
  2011. await Page.bulkWrite(operations);
  2012. }
  2013. /**
  2014. * Create revert stream
  2015. */
  2016. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  2017. if (shouldUseV4Process) {
  2018. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  2019. }
  2020. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  2021. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  2022. let count = 0;
  2023. const writeStream = new Writable({
  2024. objectMode: true,
  2025. async write(batch, encoding, callback) {
  2026. try {
  2027. count += batch.length;
  2028. await revertDeletedDescendants(batch, user);
  2029. const subscribedUsers = await Subscription.getSubscriptions(batch);
  2030. subscribedUsers.forEach((eachUser) => {
  2031. descendantsSubscribedSets.add(eachUser);
  2032. });
  2033. logger.debug(`Reverting pages progressing: (count=${count})`);
  2034. }
  2035. catch (err) {
  2036. logger.error('revertPages error on add anyway: ', err);
  2037. }
  2038. callback();
  2039. },
  2040. async final(callback) {
  2041. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  2042. callback();
  2043. },
  2044. });
  2045. readStream
  2046. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  2047. .pipe(writeStream);
  2048. await streamToPromise(writeStream);
  2049. return count;
  2050. }
  2051. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  2052. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  2053. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  2054. let count = 0;
  2055. const writeStream = new Writable({
  2056. objectMode: true,
  2057. async write(batch, encoding, callback) {
  2058. try {
  2059. count += batch.length;
  2060. await revertDeletedDescendants(batch, user);
  2061. logger.debug(`Reverting pages progressing: (count=${count})`);
  2062. }
  2063. catch (err) {
  2064. logger.error('revertPages error on add anyway: ', err);
  2065. }
  2066. callback();
  2067. },
  2068. final(callback) {
  2069. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  2070. callback();
  2071. },
  2072. });
  2073. readStream
  2074. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  2075. .pipe(writeStream);
  2076. await streamToPromise(readStream);
  2077. return count;
  2078. }
  2079. async handlePrivatePagesForGroupsToDelete(
  2080. groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[], action: PageActionOnGroupDelete, transferToUserGroup: IGrantedGroup, user,
  2081. ): Promise<void> {
  2082. const Page = mongoose.model<IPage, PageModel>('Page');
  2083. const pages = await Page.find({ grantedGroups: { $elemMatch: { item: { $in: groupsToDelete } } } });
  2084. switch (action) {
  2085. case PageActionOnGroupDelete.publicize:
  2086. await Page.removeGroupsToDeleteFromPages(pages, groupsToDelete);
  2087. break;
  2088. case PageActionOnGroupDelete.delete:
  2089. return this.deleteMultipleCompletely(pages, user);
  2090. case PageActionOnGroupDelete.transfer:
  2091. await Page.transferPagesToGroup(pages, transferToUserGroup);
  2092. break;
  2093. default:
  2094. throw new Error('Unknown action for private pages');
  2095. }
  2096. }
  2097. private extractStringIds(refs: Ref<HasObjectId>[]) {
  2098. return refs.map((ref: Ref<HasObjectId>) => {
  2099. return (typeof ref === 'string') ? ref : ref._id.toString();
  2100. });
  2101. }
  2102. constructBasicPageInfo(page: PageDocument, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
  2103. const isMovable = isGuestUser ? false : isMovablePage(page.path);
  2104. const isDeletable = !(isGuestUser || isTopPage(page.path) || isUsersTopPage(page.path));
  2105. if (page.isEmpty) {
  2106. return {
  2107. isV5Compatible: true,
  2108. isEmpty: true,
  2109. isMovable,
  2110. isDeletable: false,
  2111. isAbleToDeleteCompletely: false,
  2112. isRevertible: false,
  2113. };
  2114. }
  2115. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  2116. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  2117. return {
  2118. isV5Compatible: isTopPage(page.path) || page.parent != null,
  2119. isEmpty: false,
  2120. sumOfLikers: page.liker.length,
  2121. likerIds: this.extractStringIds(likers),
  2122. seenUserIds: this.extractStringIds(seenUsers),
  2123. sumOfSeenUsers: page.seenUsers.length,
  2124. isMovable,
  2125. isDeletable,
  2126. isAbleToDeleteCompletely: false,
  2127. isRevertible: isTrashPage(page.path),
  2128. contentAge: page.getContentAge(),
  2129. descendantCount: page.descendantCount,
  2130. commentCount: page.commentCount,
  2131. };
  2132. }
  2133. async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user?): Promise<Record<string, string | null>> {
  2134. const Page = mongoose.model('Page') as unknown as PageModel;
  2135. const MAX_LENGTH = 350;
  2136. // aggregation options
  2137. const userGroups = user != null ? [
  2138. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2139. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2140. ] : null;
  2141. const viewerCondition = Page.generateGrantCondition(user, userGroups);
  2142. const filterByIds = {
  2143. _id: { $in: pageIds },
  2144. };
  2145. let pages;
  2146. try {
  2147. pages = await Page
  2148. .aggregate([
  2149. // filter by pageIds
  2150. {
  2151. $match: filterByIds,
  2152. },
  2153. // filter by viewer
  2154. {
  2155. $match: viewerCondition,
  2156. },
  2157. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  2158. {
  2159. $lookup: {
  2160. from: 'revisions',
  2161. let: { localRevision: '$revision' },
  2162. pipeline: [
  2163. {
  2164. $match: {
  2165. $expr: {
  2166. $eq: ['$_id', '$$localRevision'],
  2167. },
  2168. },
  2169. },
  2170. {
  2171. $project: {
  2172. // What is $substrCP?
  2173. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  2174. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  2175. },
  2176. },
  2177. ],
  2178. as: 'revisionData',
  2179. },
  2180. },
  2181. // projection
  2182. {
  2183. $project: {
  2184. _id: 1,
  2185. revisionData: 1,
  2186. },
  2187. },
  2188. ]).exec();
  2189. }
  2190. catch (err) {
  2191. logger.error('Error occurred while generating shortBodiesMap');
  2192. throw err;
  2193. }
  2194. const shortBodiesMap = {};
  2195. pages.forEach((page) => {
  2196. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  2197. });
  2198. return shortBodiesMap;
  2199. }
  2200. async normalizeParentByPath(path: string, user): Promise<void> {
  2201. const Page = mongoose.model<PageDocument, PageModel>('Page');
  2202. const { PageQueryBuilder } = Page;
  2203. // This validation is not 100% correct since it ignores user to count
  2204. const builder = new PageQueryBuilder(Page.find());
  2205. builder.addConditionAsRootOrNotOnTree();
  2206. builder.addConditionToListWithDescendants(path);
  2207. const nEstimatedNormalizationTarget: number = await builder.query.exec('count');
  2208. if (nEstimatedNormalizationTarget === 0) {
  2209. throw Error('No page is available for conversion');
  2210. }
  2211. const pages = await Page.findByPathAndViewer(path, user, null, false);
  2212. if (pages == null || !Array.isArray(pages)) {
  2213. throw Error('Something went wrong while converting pages.');
  2214. }
  2215. if (pages.length === 0) {
  2216. const isForbidden = await Page.count({ path, isEmpty: false }) > 0;
  2217. if (isForbidden) {
  2218. throw new V5ConversionError('It is not allowed to convert this page.', V5ConversionErrCode.FORBIDDEN);
  2219. }
  2220. }
  2221. if (pages.length > 1) {
  2222. throw new V5ConversionError(
  2223. `There are more than two pages at the path "${path}". Please rename or delete the page first.`,
  2224. V5ConversionErrCode.DUPLICATE_PAGES_FOUND,
  2225. );
  2226. }
  2227. let page;
  2228. let systematicallyCreatedPage;
  2229. const shouldCreateNewPage = pages[0] == null;
  2230. if (shouldCreateNewPage) {
  2231. const notEmptyParent = await Page.findNotEmptyParentByPathRecursively(path);
  2232. systematicallyCreatedPage = await this.forceCreateBySystem(
  2233. path,
  2234. '',
  2235. {
  2236. grant: notEmptyParent?.grant,
  2237. grantUserIds: notEmptyParent?.grantedUsers.map(u => getIdForRef(u)),
  2238. grantUserGroupIds: notEmptyParent?.grantedGroups,
  2239. },
  2240. );
  2241. page = systematicallyCreatedPage;
  2242. }
  2243. else {
  2244. page = pages[0];
  2245. }
  2246. const grant = page.grant;
  2247. const grantedUserIds = page.grantedUsers;
  2248. const grantedGroupIds = page.grantedGroups;
  2249. /*
  2250. * UserGroup & Owner validation
  2251. */
  2252. let isGrantNormalized = false;
  2253. try {
  2254. const shouldCheckDescendants = true;
  2255. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupIds, shouldCheckDescendants);
  2256. }
  2257. catch (err) {
  2258. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2259. throw err;
  2260. }
  2261. if (!isGrantNormalized) {
  2262. throw new V5ConversionError(
  2263. 'This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.',
  2264. V5ConversionErrCode.GRANT_INVALID,
  2265. );
  2266. }
  2267. let pageOp;
  2268. try {
  2269. pageOp = await PageOperation.create({
  2270. actionType: PageActionType.NormalizeParent,
  2271. actionStage: PageActionStage.Main,
  2272. page,
  2273. user,
  2274. fromPath: page.path,
  2275. toPath: page.path,
  2276. });
  2277. }
  2278. catch (err) {
  2279. logger.error('Failed to create PageOperation document.', err);
  2280. throw err;
  2281. }
  2282. (async() => {
  2283. try {
  2284. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2285. }
  2286. catch (err) {
  2287. logger.error('Error occurred while running normalizeParentRecursivelyMainOperation.', err);
  2288. // cleanup
  2289. await PageOperation.deleteOne({ _id: pageOp._id });
  2290. throw err;
  2291. }
  2292. })();
  2293. }
  2294. async normalizeParentByPageIdsRecursively(pageIds: ObjectIdLike[], user): Promise<void> {
  2295. const Page = mongoose.model('Page') as unknown as PageModel;
  2296. const pages = await Page.findByIdsAndViewer(pageIds, user, null);
  2297. if (pages == null || pages.length === 0) {
  2298. throw Error('pageIds is null or 0 length.');
  2299. }
  2300. if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  2301. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  2302. }
  2303. await this.normalizeParentRecursivelyByPages(pages, user);
  2304. return;
  2305. }
  2306. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  2307. const Page = await mongoose.model('Page') as unknown as PageModel;
  2308. const socket = this.crowi.socketIoService.getDefaultSocket();
  2309. for await (const pageId of pageIds) {
  2310. const page = await Page.findById(pageId);
  2311. if (page == null) {
  2312. continue;
  2313. }
  2314. const errorData: PageMigrationErrorData = { paths: [page.path] };
  2315. try {
  2316. const canOperate = await this.crowi.pageOperationService.canOperate(false, page.path, page.path);
  2317. if (!canOperate) {
  2318. throw Error(`Cannot operate normalizeParent to path "${page.path}" right now.`);
  2319. }
  2320. const normalizedPage = await this.normalizeParentByPage(page, user);
  2321. if (normalizedPage == null) {
  2322. socket.emit(SocketEventName.PageMigrationError, errorData);
  2323. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  2324. }
  2325. }
  2326. catch (err) {
  2327. socket.emit(SocketEventName.PageMigrationError, errorData);
  2328. logger.error('Something went wrong while normalizing parent.', err);
  2329. }
  2330. }
  2331. socket.emit(SocketEventName.PageMigrationSuccess);
  2332. }
  2333. private async normalizeParentByPage(page, user) {
  2334. const Page = mongoose.model('Page') as unknown as PageModel;
  2335. const {
  2336. path, grant, grantedUsers: grantedUserIds, grantedGroups: grantedGroupIds,
  2337. } = page;
  2338. // check if any page exists at target path already
  2339. const existingPage = await Page.findOne({ path, parent: { $ne: null } });
  2340. if (existingPage != null && !existingPage.isEmpty) {
  2341. throw Error('Page already exists. Please rename the page to continue.');
  2342. }
  2343. /*
  2344. * UserGroup & Owner validation
  2345. */
  2346. if (grant !== Page.GRANT_RESTRICTED) {
  2347. let isGrantNormalized = false;
  2348. try {
  2349. const shouldCheckDescendants = true;
  2350. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupIds, shouldCheckDescendants);
  2351. }
  2352. catch (err) {
  2353. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2354. throw err;
  2355. }
  2356. if (!isGrantNormalized) {
  2357. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  2358. }
  2359. }
  2360. else {
  2361. throw Error('Restricted pages can not be migrated');
  2362. }
  2363. let normalizedPage;
  2364. // replace if empty page exists
  2365. if (existingPage != null && existingPage.isEmpty) {
  2366. // Inherit descendantCount from the empty page
  2367. const updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { descendantCount: existingPage.descendantCount }, { new: true });
  2368. await Page.replaceTargetWithPage(existingPage, updatedPage, true);
  2369. normalizedPage = await Page.findById(page._id);
  2370. }
  2371. else {
  2372. const parent = await this.getParentAndFillAncestorsByUser(user, page.path);
  2373. normalizedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
  2374. }
  2375. // Update descendantCount
  2376. const inc = 1;
  2377. await this.updateDescendantCountOfAncestors(normalizedPage.parent, inc, true);
  2378. return normalizedPage;
  2379. }
  2380. async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
  2381. /*
  2382. * Main Operation
  2383. */
  2384. const socket = this.crowi.socketIoService.getDefaultSocket();
  2385. const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
  2386. let normalizablePages;
  2387. let nonNormalizablePages;
  2388. try {
  2389. [normalizablePages, nonNormalizablePages] = await this.pageGrantService.separateNormalizableAndNotNormalizablePages(user, pagesToNormalize);
  2390. }
  2391. catch (err) {
  2392. socket.emit(SocketEventName.PageMigrationError);
  2393. throw err;
  2394. }
  2395. if (normalizablePages.length === 0) {
  2396. socket.emit(SocketEventName.PageMigrationError);
  2397. return;
  2398. }
  2399. if (nonNormalizablePages.length !== 0) {
  2400. const nonNormalizablePagePaths: string[] = nonNormalizablePages.map(p => p.path);
  2401. socket.emit(SocketEventName.PageMigrationError, { paths: nonNormalizablePagePaths });
  2402. logger.debug('Some pages could not be converted.', nonNormalizablePagePaths);
  2403. }
  2404. /*
  2405. * Main Operation (s)
  2406. */
  2407. const errorPagePaths: string[] = [];
  2408. for await (const page of normalizablePages) {
  2409. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, page.path);
  2410. if (!canOperate) {
  2411. errorPagePaths.push(page.path);
  2412. throw Error(`Cannot operate normalizeParentRecursiively to path "${page.path}" right now.`);
  2413. }
  2414. const Page = mongoose.model('Page') as unknown as PageModel;
  2415. const { PageQueryBuilder } = Page;
  2416. const builder = new PageQueryBuilder(Page.findOne());
  2417. builder.addConditionAsOnTree();
  2418. builder.addConditionToListByPathsArray([page.path]);
  2419. const existingPage = await builder.query.exec();
  2420. if (existingPage?.parent != null) {
  2421. errorPagePaths.push(page.path);
  2422. throw Error('This page has already converted.');
  2423. }
  2424. let pageOp;
  2425. try {
  2426. pageOp = await PageOperation.create({
  2427. actionType: PageActionType.NormalizeParent,
  2428. actionStage: PageActionStage.Main,
  2429. page,
  2430. user,
  2431. fromPath: page.path,
  2432. toPath: page.path,
  2433. });
  2434. }
  2435. catch (err) {
  2436. errorPagePaths.push(page.path);
  2437. logger.error('Failed to create PageOperation document.', err);
  2438. throw err;
  2439. }
  2440. try {
  2441. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2442. }
  2443. catch (err) {
  2444. errorPagePaths.push(page.path);
  2445. logger.error('Failed to run normalizeParentRecursivelyMainOperation.', err);
  2446. // cleanup
  2447. await PageOperation.deleteOne({ _id: pageOp._id });
  2448. throw err;
  2449. }
  2450. }
  2451. if (errorPagePaths.length === 0) {
  2452. socket.emit(SocketEventName.PageMigrationSuccess);
  2453. }
  2454. else {
  2455. socket.emit(SocketEventName.PageMigrationError, { paths: errorPagePaths });
  2456. }
  2457. }
  2458. async normalizeParentRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<number> {
  2459. // Save prevDescendantCount for sub-operation
  2460. const Page = mongoose.model('Page') as unknown as PageModel;
  2461. const { PageQueryBuilder } = Page;
  2462. const builder = new PageQueryBuilder(Page.findOne(), true);
  2463. builder.addConditionAsOnTree();
  2464. builder.addConditionToListByPathsArray([page.path]);
  2465. const exPage = await builder.query.exec();
  2466. const options = { prevDescendantCount: exPage?.descendantCount ?? 0 };
  2467. let count: number;
  2468. try {
  2469. count = await this.normalizeParentRecursively([page.path], user);
  2470. }
  2471. catch (err) {
  2472. logger.error('V5 initial miration failed.', err);
  2473. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  2474. throw err;
  2475. }
  2476. // Set to Sub
  2477. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  2478. if (pageOp == null) {
  2479. throw Error('PageOperation document not found');
  2480. }
  2481. await this.normalizeParentRecursivelySubOperation(page, user, pageOp._id, options);
  2482. return count;
  2483. }
  2484. async normalizeParentRecursivelySubOperation(page, user, pageOpId: ObjectIdLike, options: {prevDescendantCount: number}): Promise<void> {
  2485. const Page = mongoose.model('Page') as unknown as PageModel;
  2486. try {
  2487. // update descendantCount of self and descendant pages first
  2488. await this.updateDescendantCountOfSelfAndDescendants(page.path);
  2489. // find pages again to get updated descendantCount
  2490. // then calculate inc
  2491. const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
  2492. if (pageAfterUpdatingDescendantCount == null) {
  2493. throw Error('Page not found after updating descendantCount');
  2494. }
  2495. const { prevDescendantCount } = options;
  2496. const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
  2497. let inc = newDescendantCount - prevDescendantCount;
  2498. const isAlreadyConverted = page.parent != null;
  2499. if (!isAlreadyConverted) {
  2500. inc += 1;
  2501. }
  2502. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  2503. }
  2504. catch (err) {
  2505. logger.error('Failed to update descendantCount after normalizing parent:', err);
  2506. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  2507. }
  2508. await PageOperation.findByIdAndDelete(pageOpId);
  2509. }
  2510. async _isPagePathIndexUnique() {
  2511. const Page = this.crowi.model('Page');
  2512. const now = (new Date()).toString();
  2513. const path = `growi_check_is_path_index_unique_${now}`;
  2514. let isUnique = false;
  2515. try {
  2516. await Page.insertMany([
  2517. { path },
  2518. { path },
  2519. ]);
  2520. }
  2521. catch (err) {
  2522. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  2523. isUnique = true;
  2524. logger.info('Page path index is unique.');
  2525. }
  2526. else {
  2527. throw err;
  2528. }
  2529. }
  2530. finally {
  2531. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  2532. }
  2533. return isUnique;
  2534. }
  2535. async normalizeAllPublicPages() {
  2536. let isUnique;
  2537. try {
  2538. isUnique = await this._isPagePathIndexUnique();
  2539. }
  2540. catch (err) {
  2541. logger.error('Failed to check path index status', err);
  2542. throw err;
  2543. }
  2544. // drop unique index first
  2545. if (isUnique) {
  2546. try {
  2547. await this._v5NormalizeIndex();
  2548. }
  2549. catch (err) {
  2550. logger.error('V5 index normalization failed.', err);
  2551. throw err;
  2552. }
  2553. }
  2554. // then migrate
  2555. try {
  2556. await this.normalizeParentRecursively(['/'], null, false, true);
  2557. }
  2558. catch (err) {
  2559. logger.error('V5 initial miration failed.', err);
  2560. throw err;
  2561. }
  2562. // update descendantCount of all public pages
  2563. try {
  2564. await this.updateDescendantCountOfSelfAndDescendants('/');
  2565. logger.info('Successfully updated all descendantCount of public pages.');
  2566. }
  2567. catch (err) {
  2568. logger.error('Failed updating descendantCount of public pages.', err);
  2569. throw err;
  2570. }
  2571. await this._setIsV5CompatibleTrue();
  2572. }
  2573. private async _setIsV5CompatibleTrue() {
  2574. try {
  2575. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  2576. 'app:isV5Compatible': true,
  2577. });
  2578. logger.info('Successfully migrated all public pages.');
  2579. }
  2580. catch (err) {
  2581. logger.warn('Failed to update app:isV5Compatible to true.');
  2582. throw err;
  2583. }
  2584. }
  2585. private async normalizeParentAndDescendantCountOfDescendants(path: string, user, isDuplicateOperation = false): Promise<void> {
  2586. await this.normalizeParentRecursively([path], user, isDuplicateOperation);
  2587. // update descendantCount of descendant pages
  2588. await this.updateDescendantCountOfSelfAndDescendants(path);
  2589. }
  2590. /**
  2591. * Normalize parent attribute by passing paths and user.
  2592. * @param paths Pages under this paths value will be updated.
  2593. * @param user To be used to filter pages to update. If null, only public pages will be updated.
  2594. * @returns Promise<void>
  2595. */
  2596. async normalizeParentRecursively(paths: string[], user: any | null, isDuplicateOperation = false, shouldEmitProgress = false): Promise<number> {
  2597. const Page = mongoose.model('Page') as unknown as PageModel;
  2598. const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p, []));
  2599. // targets' descendants
  2600. const pathAndRegExpsToNormalize: (RegExp | string)[] = paths
  2601. .map(p => new RegExp(`^${escapeStringRegexp(addTrailingSlash(p))}`, 'i'));
  2602. // include targets' path
  2603. pathAndRegExpsToNormalize.push(...paths);
  2604. // determine UserGroup condition
  2605. const userGroups = user != null ? [
  2606. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2607. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2608. ] : null;
  2609. const grantFiltersByUser: { $or: any[] } | null = !isDuplicateOperation ? Page.generateGrantCondition(user, userGroups) : null;
  2610. return this._normalizeParentRecursively(pathAndRegExpsToNormalize, ancestorPaths, user, grantFiltersByUser, shouldEmitProgress);
  2611. }
  2612. private buildFilterForNormalizeParentRecursively(
  2613. pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser?: { $or: any[] } | null,
  2614. ) {
  2615. const Page = mongoose.model('Page') as unknown as PageModel;
  2616. const andFilter: any = {
  2617. $and: [
  2618. {
  2619. parent: null,
  2620. status: Page.STATUS_PUBLISHED,
  2621. path: { $ne: '/' },
  2622. },
  2623. ],
  2624. };
  2625. const orFilter: any = { $or: [] };
  2626. // specified pathOrRegExps
  2627. if (pathOrRegExps.length > 0) {
  2628. orFilter.$or.push(
  2629. {
  2630. path: { $in: pathOrRegExps },
  2631. },
  2632. );
  2633. }
  2634. // not specified but ancestors of specified pathOrRegExps
  2635. if (publicPathsToNormalize.length > 0) {
  2636. orFilter.$or.push(
  2637. {
  2638. path: { $in: publicPathsToNormalize },
  2639. grant: Page.GRANT_PUBLIC, // use only public pages to complete the tree
  2640. },
  2641. );
  2642. }
  2643. // Merge filters
  2644. const mergedFilter = {
  2645. $and: [
  2646. { $and: grantFiltersByUser != null ? [grantFiltersByUser, ...andFilter.$and] : [...andFilter.$and] },
  2647. { $or: orFilter.$or },
  2648. ],
  2649. };
  2650. return mergedFilter;
  2651. }
  2652. private async _normalizeParentRecursively(
  2653. pathOrRegExps: (RegExp | string)[],
  2654. publicPathsToNormalize: string[],
  2655. user,
  2656. grantFiltersByUser: { $or: any[] } | null,
  2657. shouldEmitProgress = false,
  2658. count = 0,
  2659. skiped = 0,
  2660. isFirst = true,
  2661. ): Promise<number> {
  2662. const BATCH_SIZE = 100;
  2663. const PAGES_LIMIT = 1000;
  2664. const socket = shouldEmitProgress ? this.crowi.socketIoService.getAdminSocket() : null;
  2665. const Page = mongoose.model('Page') as unknown as PageModel;
  2666. const { PageQueryBuilder } = Page;
  2667. // Build filter
  2668. const matchFilter = this.buildFilterForNormalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser);
  2669. let baseAggregation = Page
  2670. .aggregate([
  2671. { $match: matchFilter },
  2672. {
  2673. $project: { // minimize data to fetch
  2674. _id: 1,
  2675. path: 1,
  2676. },
  2677. },
  2678. ]);
  2679. // Limit pages to get
  2680. const total = await Page.countDocuments(matchFilter);
  2681. if (isFirst) {
  2682. socket?.emit(SocketEventName.PMStarted, { total });
  2683. }
  2684. if (total > PAGES_LIMIT) {
  2685. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  2686. }
  2687. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  2688. const batchStream = createBatchStream(BATCH_SIZE);
  2689. let shouldContinue = true;
  2690. let nextCount = count;
  2691. let nextSkiped = skiped;
  2692. // eslint-disable-next-line max-len
  2693. const buildPipelineToCreateEmptyPagesByUser = this.buildPipelineToCreateEmptyPagesByUser.bind(this);
  2694. const migratePagesStream = new Writable({
  2695. objectMode: true,
  2696. async write(pages, encoding, callback) {
  2697. const parentPaths = Array.from(new Set<string>(pages.map(p => pathlib.dirname(p.path))));
  2698. // 1. Remove unnecessary empty pages & reset parent for pages which had had those empty pages
  2699. const pageIdsToNotDelete = pages.map(p => p._id);
  2700. const emptyPagePathsToDelete = pages.map(p => p.path);
  2701. const builder1 = new PageQueryBuilder(Page.find({ isEmpty: true }, { _id: 1 }), true);
  2702. builder1.addConditionToListByPathsArray(emptyPagePathsToDelete);
  2703. builder1.addConditionToExcludeByPageIdsArray(pageIdsToNotDelete);
  2704. const emptyPagesToDelete = await builder1.query.lean().exec();
  2705. const resetParentOperations = emptyPagesToDelete.map((p) => {
  2706. return {
  2707. updateOne: {
  2708. filter: {
  2709. parent: p._id,
  2710. },
  2711. update: {
  2712. parent: null,
  2713. },
  2714. },
  2715. };
  2716. });
  2717. await Page.bulkWrite(resetParentOperations);
  2718. await Page.removeEmptyPages(pageIdsToNotDelete, emptyPagePathsToDelete);
  2719. // 2. Create lacking parents as empty pages
  2720. const orFilters = [
  2721. { path: '/' },
  2722. { path: { $in: publicPathsToNormalize }, grant: Page.GRANT_PUBLIC, status: Page.STATUS_PUBLISHED },
  2723. { path: { $in: publicPathsToNormalize }, parent: { $ne: null }, status: Page.STATUS_PUBLISHED },
  2724. { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
  2725. ];
  2726. const filterForApplicableAncestors = { $or: orFilters };
  2727. const aggregationPipeline = await buildPipelineToCreateEmptyPagesByUser(user, parentPaths, false, filterForApplicableAncestors);
  2728. await Page.createEmptyPagesByPaths(parentPaths, aggregationPipeline);
  2729. // 3. Find parents
  2730. const builder2 = new PageQueryBuilder(Page.find(), true);
  2731. if (grantFiltersByUser != null) {
  2732. builder2.query = builder2.query.and(grantFiltersByUser);
  2733. }
  2734. const parents = await builder2
  2735. .addConditionToListByPathsArray(parentPaths)
  2736. .addConditionToFilterByApplicableAncestors(publicPathsToNormalize)
  2737. .query
  2738. .lean()
  2739. .exec();
  2740. // Normalize all siblings for each page
  2741. const updateManyOperations = parents.map((parent) => {
  2742. const parentId = parent._id;
  2743. // Build filter
  2744. const parentPathEscaped = escapeStringRegexp(parent.path === '/' ? '' : parent.path); // adjust the path for RegExp
  2745. const filter: any = {
  2746. $and: [
  2747. {
  2748. path: { $regex: new RegExp(`^${parentPathEscaped}(\\/[^/]+)\\/?$`, 'i') }, // see: regexr.com/6889f (e.g. /parent/any_child or /any_level1)
  2749. },
  2750. {
  2751. path: { $in: pathOrRegExps.concat(publicPathsToNormalize) },
  2752. },
  2753. filterForApplicableAncestors,
  2754. ],
  2755. };
  2756. if (grantFiltersByUser != null) {
  2757. filter.$and.push(grantFiltersByUser);
  2758. }
  2759. return {
  2760. updateMany: {
  2761. filter,
  2762. update: {
  2763. parent: parentId,
  2764. },
  2765. },
  2766. };
  2767. });
  2768. try {
  2769. const res = await Page.bulkWrite(updateManyOperations);
  2770. nextCount += res.result.nModified;
  2771. nextSkiped += res.result.writeErrors.length;
  2772. logger.info(`Page migration processing: (migratedPages=${res.result.nModified})`);
  2773. socket?.emit(SocketEventName.PMMigrating, { count: nextCount });
  2774. socket?.emit(SocketEventName.PMErrorCount, { skip: nextSkiped });
  2775. // Throw if any error is found
  2776. if (res.result.writeErrors.length > 0) {
  2777. logger.error('Failed to migrate some pages', res.result.writeErrors);
  2778. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2779. throw Error('Failed to migrate some pages');
  2780. }
  2781. // Finish migration if no modification occurred
  2782. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  2783. shouldContinue = false;
  2784. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  2785. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2786. }
  2787. }
  2788. catch (err) {
  2789. logger.error('Failed to update page.parent.', err);
  2790. throw err;
  2791. }
  2792. callback();
  2793. },
  2794. final(callback) {
  2795. callback();
  2796. },
  2797. });
  2798. pagesStream
  2799. .pipe(batchStream)
  2800. .pipe(migratePagesStream);
  2801. await streamToPromise(migratePagesStream);
  2802. if (await Page.exists(matchFilter) && shouldContinue) {
  2803. return this._normalizeParentRecursively(
  2804. pathOrRegExps,
  2805. publicPathsToNormalize,
  2806. user,
  2807. grantFiltersByUser,
  2808. shouldEmitProgress,
  2809. nextCount,
  2810. nextSkiped,
  2811. false,
  2812. );
  2813. }
  2814. // End
  2815. socket?.emit(SocketEventName.PMEnded, { isSucceeded: true });
  2816. return nextCount;
  2817. }
  2818. private async _v5NormalizeIndex() {
  2819. const collection = mongoose.connection.collection('pages');
  2820. try {
  2821. // drop pages.path_1 indexes
  2822. await collection.dropIndex('path_1');
  2823. logger.info('Succeeded to drop unique indexes from pages.path.');
  2824. }
  2825. catch (err) {
  2826. logger.warn('Failed to drop unique indexes from pages.path.', err);
  2827. throw err;
  2828. }
  2829. try {
  2830. // create indexes without
  2831. await collection.createIndex({ path: 1 }, { unique: false });
  2832. logger.info('Succeeded to create non-unique indexes on pages.path.');
  2833. }
  2834. catch (err) {
  2835. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  2836. throw err;
  2837. }
  2838. }
  2839. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  2840. if (user == null) {
  2841. throw Error('user is required');
  2842. }
  2843. const Page = mongoose.model('Page') as unknown as PageModel;
  2844. const { PageQueryBuilder } = Page;
  2845. const builder = new PageQueryBuilder(Page.count(), false);
  2846. await builder.addConditionAsMigratablePages(user);
  2847. const nMigratablePages = await builder.query.exec();
  2848. return nMigratablePages;
  2849. }
  2850. /**
  2851. * update descendantCount of the following pages
  2852. * - page that has the same path as the provided path
  2853. * - pages that are descendants of the above page
  2854. */
  2855. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  2856. const BATCH_SIZE = 200;
  2857. const Page = this.crowi.model('Page');
  2858. const { PageQueryBuilder } = Page;
  2859. const builder = new PageQueryBuilder(Page.find(), true);
  2860. builder.addConditionAsOnTree();
  2861. builder.addConditionToListWithDescendants(path);
  2862. builder.addConditionToSortPagesByDescPath();
  2863. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2864. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2865. }
  2866. /**
  2867. * update descendantCount of the pages sequentially from longer path to shorter path
  2868. */
  2869. async updateDescendantCountOfPagesWithPaths(paths: string[]): Promise<void> {
  2870. const BATCH_SIZE = 200;
  2871. const Page = this.crowi.model('Page');
  2872. const { PageQueryBuilder } = Page;
  2873. const builder = new PageQueryBuilder(Page.find(), true);
  2874. builder.addConditionToListByPathsArray(paths); // find by paths
  2875. builder.addConditionToSortPagesByDescPath(); // sort in DESC
  2876. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2877. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2878. }
  2879. /**
  2880. * Recount descendantCount of pages one by one
  2881. */
  2882. async recountAndUpdateDescendantCountOfPages(pageCursor: Cursor<any>, batchSize:number): Promise<void> {
  2883. const Page = this.crowi.model('Page');
  2884. const recountWriteStream = new Writable({
  2885. objectMode: true,
  2886. async write(pageDocuments, encoding, callback) {
  2887. for await (const document of pageDocuments) {
  2888. const descendantCount = await Page.recountDescendantCount(document._id);
  2889. await Page.findByIdAndUpdate(document._id, { descendantCount });
  2890. }
  2891. callback();
  2892. },
  2893. final(callback) {
  2894. callback();
  2895. },
  2896. });
  2897. pageCursor
  2898. .pipe(createBatchStream(batchSize))
  2899. .pipe(recountWriteStream);
  2900. await streamToPromise(recountWriteStream);
  2901. }
  2902. // update descendantCount of all pages that are ancestors of a provided pageId by count
  2903. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  2904. const Page = this.crowi.model('Page');
  2905. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  2906. const ancestorPageIds = ancestors.map(p => p._id);
  2907. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  2908. const updateDescCountData: UpdateDescCountRawData = Object.fromEntries(ancestors.map(p => [p._id.toString(), p.descendantCount + inc]));
  2909. this.emitUpdateDescCount(updateDescCountData);
  2910. }
  2911. private emitUpdateDescCount(data: UpdateDescCountRawData): void {
  2912. const socket = this.crowi.socketIoService.getDefaultSocket();
  2913. socket.emit(SocketEventName.UpdateDescCount, data);
  2914. }
  2915. /**
  2916. * Build the base aggregation pipeline for fillAncestors--- methods
  2917. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  2918. * an empty page will not be created at that page's path.
  2919. */
  2920. private buildBasePipelineToCreateEmptyPages(paths: string[], onlyMigratedAsExistingPages = true, andFilter?): any[] {
  2921. const aggregationPipeline: any[] = [];
  2922. const Page = mongoose.model('Page') as unknown as PageModel;
  2923. // -- Filter by paths
  2924. aggregationPipeline.push({ $match: { path: { $in: paths } } });
  2925. // -- Normalized condition
  2926. if (onlyMigratedAsExistingPages) {
  2927. aggregationPipeline.push({
  2928. $match: {
  2929. $or: [
  2930. { grant: Page.GRANT_PUBLIC },
  2931. { parent: { $ne: null } },
  2932. { path: '/' },
  2933. ],
  2934. },
  2935. });
  2936. }
  2937. // -- Add custom pipeline
  2938. if (andFilter != null) {
  2939. aggregationPipeline.push({ $match: andFilter });
  2940. }
  2941. return aggregationPipeline;
  2942. }
  2943. private async buildPipelineToCreateEmptyPagesByUser(user, paths: string[], onlyMigratedAsExistingPages = true, andFilter?): Promise<any[]> {
  2944. const Page = mongoose.model('Page') as unknown as PageModel;
  2945. const pipeline = this.buildBasePipelineToCreateEmptyPages(paths, onlyMigratedAsExistingPages, andFilter);
  2946. const userGroups = user != null ? [
  2947. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2948. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2949. ] : null;
  2950. const grantCondition = Page.generateGrantCondition(user, userGroups);
  2951. pipeline.push({ $match: grantCondition });
  2952. return pipeline;
  2953. }
  2954. private buildPipelineToCreateEmptyPagesBySystem(paths: string[]): any[] {
  2955. return this.buildBasePipelineToCreateEmptyPages(paths);
  2956. }
  2957. private async connectPageTree(path: string): Promise<void> {
  2958. const Page = mongoose.model('Page') as unknown as PageModel;
  2959. const { PageQueryBuilder } = Page;
  2960. const ancestorPaths = collectAncestorPaths(path);
  2961. // Find ancestors
  2962. const builder = new PageQueryBuilder(Page.find(), true);
  2963. builder.addConditionToFilterByApplicableAncestors(ancestorPaths); // avoid including not normalized pages
  2964. const ancestors = await builder
  2965. .addConditionToListByPathsArray(ancestorPaths)
  2966. .addConditionToSortPagesByDescPath()
  2967. .query
  2968. .exec();
  2969. // Update parent attrs
  2970. const ancestorsMap = new Map(); // Map<path, page>
  2971. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  2972. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  2973. const operations = nonRootAncestors.map((page) => {
  2974. const parentPath = pathlib.dirname(page.path);
  2975. return {
  2976. updateOne: {
  2977. filter: {
  2978. _id: page._id,
  2979. },
  2980. update: {
  2981. parent: ancestorsMap.get(parentPath)._id,
  2982. },
  2983. },
  2984. };
  2985. });
  2986. await Page.bulkWrite(operations);
  2987. }
  2988. /**
  2989. * Find parent or create parent if not exists.
  2990. * It also updates parent of ancestors
  2991. * @param path string
  2992. * @returns Promise<PageDocument>
  2993. */
  2994. async getParentAndFillAncestorsByUser(user, path: string): Promise<PageDocument> {
  2995. const Page = mongoose.model('Page') as unknown as PageModel;
  2996. // Find parent
  2997. const parent = await Page.findParentByPath(path);
  2998. if (parent != null) {
  2999. return parent;
  3000. }
  3001. const ancestorPaths = collectAncestorPaths(path);
  3002. // Fill ancestors
  3003. const aggregationPipeline: any[] = await this.buildPipelineToCreateEmptyPagesByUser(user, ancestorPaths);
  3004. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  3005. // Connect ancestors
  3006. await this.connectPageTree(path);
  3007. // Return the created parent
  3008. const createdParent = await Page.findParentByPath(path);
  3009. if (createdParent == null) {
  3010. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  3011. }
  3012. return createdParent;
  3013. }
  3014. async getParentAndFillAncestorsBySystem(path: string): Promise<PageDocument> {
  3015. const Page = mongoose.model('Page') as unknown as PageModel;
  3016. // Find parent
  3017. const parent = await Page.findParentByPath(path);
  3018. if (parent != null) {
  3019. return parent;
  3020. }
  3021. // Fill ancestors
  3022. const ancestorPaths = collectAncestorPaths(path);
  3023. const aggregationPipeline: any[] = this.buildPipelineToCreateEmptyPagesBySystem(ancestorPaths);
  3024. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  3025. // Connect ancestors
  3026. await this.connectPageTree(path);
  3027. // Return the created parent
  3028. const createdParent = await Page.findParentByPath(path);
  3029. if (createdParent == null) {
  3030. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  3031. }
  3032. return createdParent;
  3033. }
  3034. // --------- Create ---------
  3035. private async preparePageDocumentToCreate(path: string, shouldNew: boolean): Promise<PageDocument> {
  3036. const Page = mongoose.model('Page') as unknown as PageModel;
  3037. const emptyPage = await Page.findOne({ path, isEmpty: true });
  3038. // Use empty page if exists, if not, create a new page
  3039. let page;
  3040. if (shouldNew) {
  3041. page = new Page();
  3042. }
  3043. else if (emptyPage != null) {
  3044. page = emptyPage;
  3045. const descendantCount = await Page.recountDescendantCount(page._id);
  3046. page.descendantCount = descendantCount;
  3047. page.isEmpty = false;
  3048. }
  3049. else {
  3050. page = new Page();
  3051. }
  3052. return page;
  3053. }
  3054. private setFieldExceptForGrantRevisionParent(
  3055. pageDocument: PageDocument,
  3056. path: string,
  3057. user?,
  3058. ): void {
  3059. const Page = mongoose.model('Page') as unknown as PageModel;
  3060. pageDocument.path = path;
  3061. pageDocument.creator = user;
  3062. pageDocument.lastUpdateUser = user;
  3063. pageDocument.status = Page.STATUS_PUBLISHED;
  3064. }
  3065. private async validateAppliedScope(user, grant, grantUserGroupIds: IGrantedGroup[]) {
  3066. if (grant === PageGrant.GRANT_USER_GROUP && grantUserGroupIds == null) {
  3067. throw new Error('grantUserGroupIds is not specified');
  3068. }
  3069. if (grant === PageGrant.GRANT_USER_GROUP) {
  3070. const { grantedUserGroups: grantedUserGroupIds, grantedExternalUserGroups: grantedExternalUserGroupIds } = divideByType(grantUserGroupIds);
  3071. const count = await UserGroupRelation.countByGroupIdsAndUser(grantedUserGroupIds, user)
  3072. + await ExternalUserGroupRelation.countByGroupIdsAndUser(grantedExternalUserGroupIds, user);
  3073. if (count === 0) {
  3074. throw new Error('no relations were exist for group and user.');
  3075. }
  3076. }
  3077. }
  3078. private async canProcessCreate(
  3079. path: string,
  3080. grantData: {
  3081. grant?: PageGrant,
  3082. grantUserIds?: ObjectIdLike[],
  3083. grantUserGroupIds?: IGrantedGroup[],
  3084. },
  3085. shouldValidateGrant: boolean,
  3086. user?,
  3087. options?: IOptionsForCreate,
  3088. ): Promise<boolean> {
  3089. const Page = mongoose.model('Page') as unknown as PageModel;
  3090. // Operatability validation
  3091. const canOperate = await this.crowi.pageOperationService.canOperate(false, null, path);
  3092. if (!canOperate) {
  3093. logger.error(`Cannot operate create to path "${path}" right now.`);
  3094. return false;
  3095. }
  3096. // Existance validation
  3097. const isExist = (await Page.count({ path, isEmpty: false })) > 0; // not validate empty page
  3098. if (isExist) {
  3099. logger.error('Cannot create new page to existed path');
  3100. return false;
  3101. }
  3102. // UserGroup & Owner validation
  3103. const { grant, grantUserIds, grantUserGroupIds } = grantData;
  3104. if (shouldValidateGrant) {
  3105. if (user == null) {
  3106. throw Error('user is required to validate grant');
  3107. }
  3108. let isGrantNormalized = false;
  3109. try {
  3110. // It must check descendants as well if emptyTarget is not null
  3111. const isEmptyPageAlreadyExist = await Page.count({ path, isEmpty: true }) > 0;
  3112. const shouldCheckDescendants = isEmptyPageAlreadyExist && !options?.overwriteScopesOfDescendants;
  3113. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantUserIds, grantUserGroupIds, shouldCheckDescendants);
  3114. }
  3115. catch (err) {
  3116. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  3117. throw err;
  3118. }
  3119. if (!isGrantNormalized) {
  3120. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3121. }
  3122. if (options?.overwriteScopesOfDescendants) {
  3123. const updateGrantInfo = await this.pageGrantService.generateUpdateGrantInfoToOverwriteDescendants(user, grant, options.grantUserGroupIds);
  3124. const canOverwriteDescendants = await this.pageGrantService.canOverwriteDescendants(path, user, updateGrantInfo);
  3125. if (!canOverwriteDescendants) {
  3126. throw Error('Cannot overwrite scopes of descendants.');
  3127. }
  3128. }
  3129. }
  3130. return true;
  3131. }
  3132. /**
  3133. * Create a page
  3134. * Set options.isSynchronously to true to await all process when you want to run this method multiple times at short intervals.
  3135. */
  3136. async create(_path: string, body: string, user: HasObjectId, options: IOptionsForCreate = {}): Promise<PageDocument> {
  3137. // Switch method
  3138. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3139. if (!isV5Compatible) {
  3140. return this.createV4(_path, body, user, options);
  3141. }
  3142. // Values
  3143. const path: string = generalXssFilter.process(_path); // sanitize path
  3144. // Retrieve closest ancestor document
  3145. const Page = mongoose.model<PageDocument, PageModel>('Page');
  3146. const closestAncestor = await Page.findNonEmptyClosestAncestor(path);
  3147. // Determine grantData
  3148. const grant = options.grant ?? closestAncestor?.grant ?? PageGrant.GRANT_PUBLIC;
  3149. const grantUserIds = grant === PageGrant.GRANT_OWNER ? [user._id] : undefined;
  3150. const getGrantedGroupsFromClosestAncestor = async() => {
  3151. if (closestAncestor == null) return undefined;
  3152. if (options.onlyInheritUserRelatedGrantedGroups) {
  3153. return this.pageGrantService.getUserRelatedGrantedGroups(closestAncestor, user);
  3154. }
  3155. return closestAncestor.grantedGroups;
  3156. };
  3157. const grantUserGroupIds = options.grantUserGroupIds ?? await getGrantedGroupsFromClosestAncestor();
  3158. const grantData = {
  3159. grant,
  3160. grantUserIds,
  3161. grantUserGroupIds,
  3162. };
  3163. const isGrantRestricted = grant === PageGrant.GRANT_RESTRICTED;
  3164. // Validate
  3165. const shouldValidateGrant = !isGrantRestricted;
  3166. const canProcessCreate = await this.canProcessCreate(path, grantData, shouldValidateGrant, user, options);
  3167. if (!canProcessCreate) {
  3168. throw Error('Cannot process create');
  3169. }
  3170. // Prepare a page document
  3171. const shouldNew = isGrantRestricted;
  3172. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  3173. // Set field
  3174. this.setFieldExceptForGrantRevisionParent(page, path, user);
  3175. // Apply scope
  3176. page.applyScope(user, grant, grantUserGroupIds);
  3177. // Set parent
  3178. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  3179. page.parent = null;
  3180. }
  3181. else {
  3182. const parent = await this.getParentAndFillAncestorsByUser(user, path);
  3183. page.parent = parent._id;
  3184. }
  3185. // Make WIP
  3186. if (options.wip) {
  3187. const hasChildren = await Page.exists({ parent: page._id });
  3188. page.makeWip(hasChildren != null); // disableTtl = hasChildren != null
  3189. }
  3190. // Save
  3191. let savedPage = await page.save();
  3192. // Create revision
  3193. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  3194. const newRevision = Revision.prepareRevision(savedPage, body, null, user, options.origin);
  3195. savedPage = await pushRevision(savedPage, newRevision, user);
  3196. await savedPage.populateDataToShowRevision();
  3197. // Emit create event
  3198. this.pageEvent.emit('create', savedPage, user);
  3199. // Directly run sub operation for now since it might be complex to handle main operation for creating pages -- Taichi Masuyama 2022.11.08
  3200. let pageOp;
  3201. try {
  3202. pageOp = await PageOperation.create({
  3203. actionType: PageActionType.Create,
  3204. actionStage: PageActionStage.Sub,
  3205. page: savedPage,
  3206. user,
  3207. fromPath: path,
  3208. options,
  3209. });
  3210. }
  3211. catch (err) {
  3212. logger.error('Failed to create PageOperation document.', err);
  3213. throw err;
  3214. }
  3215. this.createSubOperation(savedPage, user, options, pageOp._id);
  3216. return savedPage;
  3217. }
  3218. /**
  3219. * Used to run sub operation in create method
  3220. */
  3221. async createSubOperation(page, user, options: IOptionsForCreate, pageOpId: ObjectIdLike): Promise<void> {
  3222. await this.disableAncestorPagesTtl(page.path);
  3223. // Update descendantCount
  3224. await this.updateDescendantCountOfAncestors(page._id, 1, false);
  3225. // Delete PageRedirect if exists
  3226. try {
  3227. await PageRedirect.deleteOne({ fromPath: page.path });
  3228. logger.warn(`Deleted page redirect after creating a new page at path "${page.path}".`);
  3229. }
  3230. catch (err) {
  3231. // no throw
  3232. logger.error('Failed to delete PageRedirect');
  3233. }
  3234. // update scopes for descendants
  3235. if (options.overwriteScopesOfDescendants) {
  3236. await this.applyScopesToDescendantsWithStream(page, user);
  3237. }
  3238. await PageOperation.findByIdAndDelete(pageOpId);
  3239. }
  3240. /**
  3241. * V4 compatible create method
  3242. */
  3243. private async createV4(path, body, user, options: any = {}) {
  3244. const Page = mongoose.model('Page') as unknown as PageModel;
  3245. const Revision = mongoose.model('Revision') as any; // TODO: TypeScriptize model
  3246. const format = options.format || 'markdown';
  3247. const grantUserGroupIds = options.grantUserGroupIds || null;
  3248. const expandContentWidth = this.crowi.configManager.getConfig('crowi', 'customize:isContainerFluid');
  3249. // sanitize path
  3250. path = generalXssFilter.process(path); // eslint-disable-line no-param-reassign
  3251. let grant = options.grant;
  3252. // force public
  3253. if (isTopPage(path)) {
  3254. grant = PageGrant.GRANT_PUBLIC;
  3255. }
  3256. const isExist = await Page.count({ path });
  3257. if (isExist) {
  3258. throw new Error('Cannot create new page to existed path');
  3259. }
  3260. const page = new Page();
  3261. page.path = path;
  3262. page.creator = user;
  3263. page.lastUpdateUser = user;
  3264. page.status = PageStatus.STATUS_PUBLISHED;
  3265. if (expandContentWidth != null) {
  3266. page.expandContentWidth = expandContentWidth;
  3267. }
  3268. await this.validateAppliedScope(user, grant, grantUserGroupIds);
  3269. page.applyScope(user, grant, grantUserGroupIds);
  3270. let savedPage = await page.save();
  3271. const newRevision = Revision.prepareRevision(savedPage, body, null, user, undefined, { format });
  3272. savedPage = await pushRevision(savedPage, newRevision, user);
  3273. await savedPage.populateDataToShowRevision();
  3274. this.pageEvent.emit('create', savedPage, user);
  3275. // update scopes for descendants
  3276. if (options.overwriteScopesOfDescendants) {
  3277. this.applyScopesToDescendantsWithStream(savedPage, user, true);
  3278. }
  3279. return savedPage;
  3280. }
  3281. private async canProcessForceCreateBySystem(
  3282. path: string,
  3283. grantData: {
  3284. grant: PageGrant,
  3285. grantUserIds?: ObjectIdLike[],
  3286. grantUserGroupId?: ObjectIdLike,
  3287. },
  3288. ): Promise<boolean> {
  3289. return this.canProcessCreate(path, grantData, false);
  3290. }
  3291. private async disableAncestorPagesTtl(path: string): Promise<void> {
  3292. const Page = mongoose.model<PageDocument, PageModel>('Page');
  3293. const ancestorPaths = collectAncestorPaths(path);
  3294. const ancestorPageIds = await Page.aggregate([
  3295. { $match: { path: { $in: ancestorPaths, $nin: ['/'] }, isEmpty: false } },
  3296. { $project: { _id: 1 } },
  3297. ]);
  3298. await Page.updateMany({ _id: { $in: ancestorPageIds } }, { $unset: { ttlTimestamp: true } });
  3299. }
  3300. /**
  3301. * @private
  3302. * This method receives the same arguments as the PageService.create method does except for the added type '{ grantUserIds?: ObjectIdLike[] }'.
  3303. * This additional value is used to determine the grantedUser of the page to be created by system.
  3304. * This method must not run isGrantNormalized method to validate grant. **If necessary, run it before use this method.**
  3305. * -- Reason 1: This is because it is not expected to use this method when the grant validation is required.
  3306. * -- Reason 2: This is because it is not expected to use this method when the program cannot determine the operator.
  3307. */
  3308. async forceCreateBySystem(path: string, body: string, options: IOptionsForCreate & { grantUserIds?: ObjectIdLike[] }): Promise<PageDocument> {
  3309. const Page = mongoose.model('Page') as unknown as PageModel;
  3310. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3311. if (!isV5Compatible) {
  3312. throw Error('This method is available only when v5 compatible');
  3313. }
  3314. // Values
  3315. // eslint-disable-next-line no-param-reassign
  3316. path = generalXssFilter.process(path); // sanitize path
  3317. const {
  3318. grantUserGroupIds, grantUserIds,
  3319. } = options;
  3320. const grant = isTopPage(path) ? Page.GRANT_PUBLIC : options.grant;
  3321. const isGrantRestricted = grant === Page.GRANT_RESTRICTED;
  3322. const isGrantOwner = grant === Page.GRANT_OWNER;
  3323. const grantData = {
  3324. grant,
  3325. grantUserIds: isGrantOwner ? grantUserIds : undefined,
  3326. grantUserGroupIds,
  3327. };
  3328. // Validate
  3329. if (isGrantOwner && grantUserIds?.length !== 1) {
  3330. throw Error('grantedUser must exist when grant is GRANT_OWNER');
  3331. }
  3332. const canProcessForceCreateBySystem = await this.canProcessForceCreateBySystem(path, grantData);
  3333. if (!canProcessForceCreateBySystem) {
  3334. throw Error('Cannot process forceCreateBySystem');
  3335. }
  3336. // Prepare a page document
  3337. const shouldNew = isGrantRestricted;
  3338. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  3339. // Set field
  3340. this.setFieldExceptForGrantRevisionParent(page, path);
  3341. // Apply scope
  3342. page.applyScope({ _id: grantUserIds?.[0] }, grant, grantUserGroupIds);
  3343. // Set parent
  3344. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  3345. page.parent = null;
  3346. }
  3347. else {
  3348. const parent = await this.getParentAndFillAncestorsBySystem(path);
  3349. page.parent = parent._id;
  3350. }
  3351. // Save
  3352. let savedPage = await page.save();
  3353. // Create revision
  3354. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  3355. const dummyUser = { _id: new mongoose.Types.ObjectId() };
  3356. const newRevision = Revision.prepareRevision(savedPage, body, null, dummyUser);
  3357. savedPage = await pushRevision(savedPage, newRevision, dummyUser);
  3358. // Update descendantCount
  3359. await this.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  3360. // Emit create event
  3361. this.pageEvent.emit('create', savedPage, dummyUser);
  3362. return savedPage;
  3363. }
  3364. private shouldUseUpdatePageV4(grant: number, isV5Compatible: boolean, isOnTree: boolean): boolean {
  3365. const isRestricted = grant === PageGrant.GRANT_RESTRICTED;
  3366. return !isRestricted && (!isV5Compatible || !isOnTree);
  3367. }
  3368. /**
  3369. * A wrapper method of updatePage for updating grant only.
  3370. * @param {PageDocument} page
  3371. * @param {UserDocument} user
  3372. * @param options
  3373. */
  3374. async updateGrant(page, user, grantData: {grant: PageGrant, userRelatedGrantedGroups: IGrantedGroup[]}): Promise<PageDocument> {
  3375. const { grant, userRelatedGrantedGroups } = grantData;
  3376. const options: IOptionsForUpdate = {
  3377. grant,
  3378. userRelatedGrantUserGroupIds: userRelatedGrantedGroups,
  3379. };
  3380. return this.updatePage(page, null, null, user, options);
  3381. }
  3382. async updatePageSubOperation(page, user, exPage, options: IOptionsForUpdate, pageOpId: ObjectIdLike): Promise<void> {
  3383. const Page = mongoose.model('Page') as unknown as PageModel;
  3384. const currentPage = page;
  3385. const exParent = exPage.parent;
  3386. const wasOnTree = exPage.parent != null || isTopPage(exPage.path);
  3387. const shouldBeOnTree = currentPage.grant !== PageGrant.GRANT_RESTRICTED;
  3388. const isChildrenExist = await Page.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(currentPage.path))}`), parent: { $ne: null } });
  3389. // 1. Update descendantCount
  3390. const shouldPlusDescCount = !wasOnTree && shouldBeOnTree;
  3391. const shouldMinusDescCount = wasOnTree && !shouldBeOnTree;
  3392. if (shouldPlusDescCount) {
  3393. await this.updateDescendantCountOfAncestors(currentPage._id, 1, false);
  3394. const newDescendantCount = await Page.recountDescendantCount(currentPage._id);
  3395. await Page.updateOne({ _id: currentPage._id }, { descendantCount: newDescendantCount });
  3396. }
  3397. else if (shouldMinusDescCount) {
  3398. // Update from parent. Parent is null if currentPage.grant is RESTRECTED.
  3399. if (currentPage.grant === PageGrant.GRANT_RESTRICTED) {
  3400. await this.updateDescendantCountOfAncestors(exParent, -1, true);
  3401. }
  3402. }
  3403. // 2. Delete unnecessary empty pages
  3404. const shouldRemoveLeafEmpPages = wasOnTree && !isChildrenExist;
  3405. if (shouldRemoveLeafEmpPages) {
  3406. await Page.removeLeafEmptyPagesRecursively(exParent);
  3407. }
  3408. // 3. Update scopes for descendants
  3409. if (options.overwriteScopesOfDescendants) {
  3410. await this.applyScopesToDescendantsWithStream(currentPage, user);
  3411. }
  3412. await PageOperation.findByIdAndDelete(pageOpId);
  3413. }
  3414. /**
  3415. * Get the new GrantedGroups for the page going through an update operation.
  3416. * It will include the groups specified by the operator, and groups which the user does not belong to, but was related to the page before the update.
  3417. * @param userRelatedGrantedGroups The groups specified by the operator
  3418. * @param page The page going through an update operation
  3419. * @param user The operator
  3420. * @returns The new GrantedGroups array to be set to the page
  3421. */
  3422. async getNewGrantedGroups(userRelatedGrantedGroups: IGrantedGroup[], page: PageDocument, user): Promise<IGrantedGroup[]> {
  3423. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  3424. return this.getNewGrantedGroupsSyncronously(userRelatedGroups, userRelatedGrantedGroups, page);
  3425. }
  3426. /**
  3427. * Use when you do not want to use getNewGrantedGroups with async/await (e.g inside loops that process a large amount of pages)
  3428. * Specification of userRelatedGroups is necessary to avoid the cost of fetching userRelatedGroups from DB every time.
  3429. */
  3430. getNewGrantedGroupsSyncronously(userRelatedGroups: PopulatedGrantedGroup[], userRelatedGrantedGroups: IGrantedGroup[], page: PageDocument): IGrantedGroup[] {
  3431. const previousGrantedGroups = page.grantedGroups;
  3432. const userRelatedPreviousGrantedGroups = this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(
  3433. userRelatedGroups, page,
  3434. ).map(g => getIdForRef(g.item));
  3435. const userUnrelatedPreviousGrantedGroups = previousGrantedGroups.filter(g => !userRelatedPreviousGrantedGroups.includes(getIdForRef(g.item)));
  3436. return [...userUnrelatedPreviousGrantedGroups, ...userRelatedGrantedGroups];
  3437. }
  3438. async updatePage(
  3439. pageData: PageDocument,
  3440. body: string | null,
  3441. previousBody: string | null,
  3442. user: IUserHasId,
  3443. options: IOptionsForUpdate = {},
  3444. ): Promise<PageDocument> {
  3445. const Page = mongoose.model('Page') as unknown as PageModel;
  3446. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  3447. const wasOnTree = pageData.parent != null || isTopPage(pageData.path);
  3448. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3449. const shouldUseV4Process = this.shouldUseUpdatePageV4(pageData.grant, isV5Compatible, wasOnTree);
  3450. if (shouldUseV4Process) {
  3451. // v4 compatible process
  3452. return this.updatePageV4(pageData, body, previousBody, user, options);
  3453. }
  3454. // Clone page document
  3455. const clonedPageData = Page.hydrate(pageData.toObject());
  3456. const newPageData = pageData;
  3457. // Once updated it's exempt from automatic deletion
  3458. if (options.wip == null) {
  3459. newPageData.ttlTimestamp = undefined;
  3460. }
  3461. else if (options.wip) {
  3462. newPageData.unpublish();
  3463. }
  3464. else {
  3465. newPageData.publish();
  3466. }
  3467. // use the previous data if absent
  3468. const grant = options.grant ?? clonedPageData.grant;
  3469. const grantUserGroupIds = options.userRelatedGrantUserGroupIds != null
  3470. ? (await this.getNewGrantedGroups(options.userRelatedGrantUserGroupIds, clonedPageData, user))
  3471. : clonedPageData.grantedGroups;
  3472. const grantedUserIds = clonedPageData.grantedUserIds || [user._id];
  3473. const shouldBeOnTree = grant !== PageGrant.GRANT_RESTRICTED;
  3474. const isChildrenExist = await Page.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(clonedPageData.path))}`), parent: { $ne: null } });
  3475. const isGrantChangeable = await this.pageGrantService.validateGrantChange(user, pageData.grantedGroups, grant, grantUserGroupIds);
  3476. if (!isGrantChangeable) {
  3477. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3478. }
  3479. if (shouldBeOnTree) {
  3480. let isGrantNormalized = false;
  3481. try {
  3482. const shouldCheckDescendants = !options.overwriteScopesOfDescendants;
  3483. // eslint-disable-next-line max-len
  3484. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, clonedPageData.path, grant, grantedUserIds, grantUserGroupIds, shouldCheckDescendants, false);
  3485. }
  3486. catch (err) {
  3487. logger.error(`Failed to validate grant of page at "${clonedPageData.path}" of grant ${grant}:`, err);
  3488. throw err;
  3489. }
  3490. if (!isGrantNormalized) {
  3491. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3492. }
  3493. if (options.overwriteScopesOfDescendants) {
  3494. const updateGrantInfo = await this.pageGrantService.generateUpdateGrantInfoToOverwriteDescendants(user, grant, options.userRelatedGrantUserGroupIds);
  3495. const canOverwriteDescendants = await this.pageGrantService.canOverwriteDescendants(clonedPageData.path, user, updateGrantInfo);
  3496. if (!canOverwriteDescendants) {
  3497. throw Error('Cannot overwrite scopes of descendants.');
  3498. }
  3499. }
  3500. if (!wasOnTree) {
  3501. const newParent = await this.getParentAndFillAncestorsByUser(user, newPageData.path);
  3502. newPageData.parent = newParent._id;
  3503. }
  3504. }
  3505. else {
  3506. if (wasOnTree && isChildrenExist) {
  3507. // Update children's parent with new parent
  3508. const newParentForChildren = await Page.createEmptyPage(clonedPageData.path, clonedPageData.parent, clonedPageData.descendantCount);
  3509. await Page.updateMany(
  3510. { parent: clonedPageData._id },
  3511. { parent: newParentForChildren._id },
  3512. );
  3513. }
  3514. newPageData.parent = null;
  3515. newPageData.descendantCount = 0;
  3516. }
  3517. newPageData.applyScope(user, grant, grantUserGroupIds);
  3518. // update existing page
  3519. let savedPage = await newPageData.save();
  3520. // Update body
  3521. const isBodyPresent = body != null;
  3522. const shouldUpdateBody = isBodyPresent;
  3523. if (shouldUpdateBody) {
  3524. const origin = options.origin;
  3525. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user, origin);
  3526. savedPage = await pushRevision(savedPage, newRevision, user);
  3527. await savedPage.populateDataToShowRevision();
  3528. }
  3529. this.pageEvent.emit('update', savedPage, user);
  3530. // Update ex children's parent
  3531. if (!wasOnTree && shouldBeOnTree) {
  3532. const emptyPageAtSamePath = await Page.findOne({ path: clonedPageData.path, isEmpty: true }); // this page is necessary to find children
  3533. if (isChildrenExist) {
  3534. if (emptyPageAtSamePath != null) {
  3535. // Update children's parent with new parent
  3536. await Page.updateMany(
  3537. { parent: emptyPageAtSamePath._id },
  3538. { parent: savedPage._id },
  3539. );
  3540. }
  3541. }
  3542. await Page.findOneAndDelete({ path: clonedPageData.path, isEmpty: true }); // delete here
  3543. }
  3544. // Directly run sub operation for now since it might be complex to handle main operation for updating pages -- Taichi Masuyama 2022.11.08
  3545. let pageOp;
  3546. try {
  3547. pageOp = await PageOperation.create({
  3548. actionType: PageActionType.Update,
  3549. actionStage: PageActionStage.Sub,
  3550. page: savedPage,
  3551. exPage: clonedPageData,
  3552. user,
  3553. fromPath: clonedPageData.path,
  3554. options,
  3555. });
  3556. }
  3557. catch (err) {
  3558. logger.error('Failed to create PageOperation document.', err);
  3559. throw err;
  3560. }
  3561. this.updatePageSubOperation(savedPage, user, clonedPageData, options, pageOp._id);
  3562. return savedPage;
  3563. }
  3564. async updatePageV4(pageData: PageDocument, body, previousBody, user, options: IOptionsForUpdate = {}): Promise<PageDocument> {
  3565. const Page = mongoose.model('Page') as unknown as PageModel;
  3566. const Revision = mongoose.model('Revision') as any; // TODO: TypeScriptize model
  3567. // use the previous data if absent
  3568. const grant = options.grant || pageData.grant;
  3569. const grantUserGroupIds = options.userRelatedGrantUserGroupIds != null
  3570. ? (await this.getNewGrantedGroups(options.userRelatedGrantUserGroupIds, pageData, user))
  3571. : pageData.grantedGroups;
  3572. // validate multiple group grant before save using pageData and options
  3573. await this.pageGrantService.validateGrantChange(user, pageData.grantedGroups, grant, grantUserGroupIds);
  3574. await this.validateAppliedScope(user, grant, grantUserGroupIds);
  3575. pageData.applyScope(user, grant, grantUserGroupIds);
  3576. // update existing page
  3577. let savedPage = await pageData.save();
  3578. // Update revision
  3579. const isBodyPresent = body != null && previousBody != null;
  3580. const shouldUpdateBody = isBodyPresent;
  3581. if (shouldUpdateBody) {
  3582. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  3583. savedPage = await pushRevision(savedPage, newRevision, user);
  3584. await savedPage.populateDataToShowRevision();
  3585. }
  3586. // update scopes for descendants
  3587. if (options.overwriteScopesOfDescendants) {
  3588. this.applyScopesToDescendantsWithStream(savedPage, user, true);
  3589. }
  3590. this.pageEvent.emit('update', savedPage, user);
  3591. return savedPage;
  3592. }
  3593. /*
  3594. * Find all children by parent's path or id. Using id should be prioritized
  3595. */
  3596. async findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  3597. const Page = mongoose.model('Page') as unknown as PageModel;
  3598. let queryBuilder: PageQueryBuilder;
  3599. if (hasSlash(parentPathOrId)) {
  3600. const path = parentPathOrId;
  3601. const regexp = generateChildrenRegExp(path);
  3602. queryBuilder = new PageQueryBuilder(Page.find({ path: { $regex: regexp } }), true);
  3603. }
  3604. else {
  3605. const parentId = parentPathOrId;
  3606. // Use $eq for user-controlled sources. see: https://codeql.github.com/codeql-query-help/javascript/js-sql-injection/#recommendation
  3607. queryBuilder = new PageQueryBuilder(Page.find({ parent: { $eq: parentId } } as any), true); // TODO: improve type
  3608. }
  3609. await queryBuilder.addViewerCondition(user, userGroups);
  3610. const pages = await queryBuilder
  3611. .addConditionToSortPagesByAscPath()
  3612. .query
  3613. .lean()
  3614. .exec();
  3615. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3616. return pages;
  3617. }
  3618. /**
  3619. * Find all pages in trash page
  3620. */
  3621. async findAllTrashPages(user: IUserHasId, userGroups = null): Promise<PageDocument[]> {
  3622. const Page = mongoose.model('Page') as unknown as PageModel;
  3623. // https://regex101.com/r/KYZWls/1
  3624. // ex. /trash/.*
  3625. const regexp = new RegExp('^/trash\\/.*$');
  3626. const queryBuilder = new PageQueryBuilder(Page.find({ path: { $regex: regexp } }), true);
  3627. await queryBuilder.addViewerCondition(user, userGroups);
  3628. const pages = await queryBuilder
  3629. .addConditionToSortPagesByAscPath()
  3630. .query
  3631. .lean()
  3632. .exec();
  3633. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3634. return pages;
  3635. }
  3636. async findAncestorsChildrenByPathAndViewer(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  3637. const Page = mongoose.model('Page') as unknown as PageModel;
  3638. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  3639. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  3640. // get pages at once
  3641. const queryBuilder = new PageQueryBuilder(Page.find({ path: { $in: regexps } }), true);
  3642. await queryBuilder.addViewerCondition(user, userGroups);
  3643. const pages = await queryBuilder
  3644. .addConditionAsOnTree()
  3645. .addConditionToMinimizeDataForRendering()
  3646. .addConditionToSortPagesByAscPath()
  3647. .query
  3648. .lean()
  3649. .exec();
  3650. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3651. /*
  3652. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  3653. */
  3654. const pathToChildren: Record<string, PageDocument[]> = {};
  3655. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  3656. sortedPaths.every((path) => {
  3657. const children = pages.filter(page => pathlib.dirname(page.path) === path);
  3658. if (children.length === 0) {
  3659. return false; // break when children do not exist
  3660. }
  3661. pathToChildren[path] = children;
  3662. return true;
  3663. });
  3664. return pathToChildren;
  3665. }
  3666. /**
  3667. * Inject processData into page docuements
  3668. * The processData is a combination of actionType as a key and information on whether the action is processable as a value.
  3669. */
  3670. private async injectProcessDataIntoPagesByActionTypes(
  3671. pages: (PageDocument & { processData?: IPageOperationProcessData })[],
  3672. actionTypes: PageActionType[],
  3673. ): Promise<void> {
  3674. const pageOperations = await PageOperation.find({ actionType: { $in: actionTypes } });
  3675. if (pageOperations == null || pageOperations.length === 0) {
  3676. return;
  3677. }
  3678. const processInfo: IPageOperationProcessInfo = this.crowi.pageOperationService.generateProcessInfo(pageOperations);
  3679. const operatingPageIds: string[] = Object.keys(processInfo);
  3680. // inject processData into pages
  3681. pages.forEach((page) => {
  3682. const pageId = page._id.toString();
  3683. if (operatingPageIds.includes(pageId)) {
  3684. const processData: IPageOperationProcessData = processInfo[pageId];
  3685. page.processData = processData;
  3686. }
  3687. });
  3688. }
  3689. async getYjsData(pageId: string): Promise<CurrentPageYjsData> {
  3690. const yjsConnectionManager = getYjsConnectionManager();
  3691. const currentYdoc = yjsConnectionManager.getCurrentYdoc(pageId);
  3692. const persistedYdoc = await yjsConnectionManager.getPersistedYdoc(pageId);
  3693. const yjsDraft = (currentYdoc ?? persistedYdoc)?.getText('codemirror').toString();
  3694. const hasRevisionBodyDiff = await this.hasRevisionBodyDiff(pageId, yjsDraft);
  3695. return {
  3696. hasRevisionBodyDiff,
  3697. awarenessStateSize: currentYdoc?.awareness.states.size,
  3698. };
  3699. }
  3700. async syncLatestRevisionBodyToYjsDraft(pageId: string): Promise<void> {
  3701. const yjsConnectionManager = getYjsConnectionManager();
  3702. // await yjsConnectionManager.mdbInstance.clearDocument(pageId);
  3703. const Revision = mongoose.model<IRevisionHasId>('Revision');
  3704. const revision = await Revision.findOne({ pageId }).sort({ createdAt: -1 });
  3705. if (revision != null) {
  3706. await yjsConnectionManager.handleYDocUpdate(pageId, revision.body);
  3707. }
  3708. }
  3709. async hasRevisionBodyDiff(pageId: string, comparisonTarget?: string): Promise<boolean> {
  3710. if (comparisonTarget == null) {
  3711. return false;
  3712. }
  3713. const Revision = mongoose.model<IRevisionHasId>('Revision');
  3714. const revision = await Revision.findOne({ pageId }).sort({ createdAt: -1 });
  3715. if (revision == null) {
  3716. return false;
  3717. }
  3718. return revision.body !== comparisonTarget;
  3719. }
  3720. async createTtlIndex(): Promise<void> {
  3721. const wipPageExpirationSeconds = configManager.getConfig('crowi', 'app:wipPageExpirationSeconds') ?? 172800;
  3722. const collection = mongoose.connection.collection('pages');
  3723. try {
  3724. const targetField = 'ttlTimestamp_1';
  3725. const indexes = await collection.indexes();
  3726. const foundTargetField = indexes.find(i => i.name === targetField);
  3727. const isNotSpec = foundTargetField?.expireAfterSeconds == null || foundTargetField?.expireAfterSeconds !== wipPageExpirationSeconds;
  3728. const shoudDropIndex = foundTargetField != null && isNotSpec;
  3729. const shoudCreateIndex = foundTargetField == null || shoudDropIndex;
  3730. if (shoudDropIndex) {
  3731. await collection.dropIndex(targetField);
  3732. }
  3733. if (shoudCreateIndex) {
  3734. await collection.createIndex({ ttlTimestamp: 1 }, { expireAfterSeconds: wipPageExpirationSeconds });
  3735. }
  3736. }
  3737. catch (err) {
  3738. logger.error('Failed to create TTL Index', err);
  3739. throw err;
  3740. }
  3741. }
  3742. }
  3743. export default PageService;