index.ts 150 KB

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