index.ts 152 KB

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