page.ts 136 KB

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