privatebin.js 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260
  1. 'use strict';
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @see {@link https://github.com/PrivateBin/PrivateBin}
  8. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  9. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. /**
  14. * draghover plugin replacement
  15. * adds draghoverstart and draghoverend events to an element
  16. */
  17. function draghover(element) {
  18. let collection = new Set();
  19. element.addEventListener('dragenter', function (e) {
  20. if (collection.size === 0) {
  21. element.dispatchEvent(new CustomEvent('draghoverstart'));
  22. }
  23. collection.add(e.target);
  24. });
  25. element.addEventListener('dragleave', function (e) {
  26. collection.delete(e.target);
  27. if (collection.size === 0) {
  28. element.dispatchEvent(new CustomEvent('draghoverend'));
  29. }
  30. });
  31. element.addEventListener('drop', function (e) {
  32. collection.delete(e.target);
  33. if (collection.size === 0) {
  34. element.dispatchEvent(new CustomEvent('draghoverend'));
  35. }
  36. });
  37. }
  38. window.PrivateBin = (function () {
  39. /**
  40. * zlib library interface
  41. *
  42. * @private
  43. */
  44. let z;
  45. /**
  46. * DOMpurify settings for HTML content
  47. *
  48. * @private
  49. */
  50. const purifyHtmlConfig = {
  51. ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i,
  52. FORBID_ATTR: ['id', 'class', 'style'],
  53. USE_PROFILES: {
  54. html: true
  55. }
  56. };
  57. /**
  58. * DOMpurify settings for HTML content, where only a strict subset is allowed.
  59. *
  60. * NOTE: The key {@link purifyHtmlConfig.USE_PROFILES} **must not** be included,
  61. * as otherwise `USE_PROFILES` takes precedence over {@link purifyHtmlConfigStrictSubset.ALLOWED_TAGS}.
  62. *
  63. * @private
  64. */
  65. const purifyHtmlConfigStrictSubset = {
  66. ALLOWED_URI_REGEXP: purifyHtmlConfig.ALLOWED_URI_REGEXP,
  67. ALLOWED_TAGS: ['a'],
  68. ALLOWED_ATTR: ['href']
  69. };
  70. /**
  71. * DOMpurify settings for SVG content
  72. *
  73. * @private
  74. */
  75. const purifySvgConfig = {
  76. USE_PROFILES: {
  77. svg: true,
  78. svgFilters: true
  79. }
  80. };
  81. /**
  82. * DOMpurify settings for translated messages, which are allowed to include limited HTML.
  83. *
  84. * NOTE: The key {@link purifyHtmlConfig.USE_PROFILES} **must not** be included,
  85. * as otherwise `USE_PROFILES` takes precedence over {@link purifyHtmlConfigStrictSubset.ALLOWED_TAGS}.
  86. *
  87. * @private
  88. */
  89. const purifyTranslationConfig = {
  90. ALLOWED_URI_REGEXP: /^(?:https?:)/i, // the only URL expected here is the generated document, so only http & https
  91. ALLOWED_TAGS: ['a', 'i', 'span', 'kbd'],
  92. ALLOWED_ATTR: ['href', 'id'] // one of the messages contains an id attribute
  93. };
  94. /**
  95. * URL fragment prefix requiring load confirmation
  96. *
  97. * @private
  98. */
  99. const loadConfirmPrefix = '#-';
  100. /**
  101. * CryptoData class
  102. *
  103. * bundles helper functions used in both document and comment formats
  104. *
  105. * @name CryptoData
  106. * @class
  107. */
  108. function CryptoData(data) {
  109. // store all keys in the default locations for drop-in replacement
  110. for (const key in data) {
  111. if (Object.prototype.hasOwnProperty.call(data, key)) {
  112. this[key] = data[key];
  113. }
  114. }
  115. /**
  116. * gets the cipher data (cipher text + adata)
  117. *
  118. * @name CryptoData.getCipherData
  119. * @function
  120. * @return {Array}
  121. */
  122. this.getCipherData = function () {
  123. return [this.ct, this.adata];
  124. };
  125. }
  126. /**
  127. * Paste class
  128. *
  129. * bundles helper functions around the document formats
  130. *
  131. * @name Paste
  132. * @class
  133. */
  134. function Paste(data) {
  135. // inherit constructor and methods of CryptoData
  136. CryptoData.call(this, data);
  137. /**
  138. * gets the used formatter
  139. *
  140. * @name Paste.getFormat
  141. * @function
  142. * @return {string}
  143. */
  144. this.getFormat = function () {
  145. return this.adata[1];
  146. };
  147. /**
  148. * gets the remaining seconds before the document expires
  149. *
  150. * returns 0 if there is no expiration
  151. *
  152. * @name Paste.getTimeToLive
  153. * @function
  154. * @return {string}
  155. */
  156. this.getTimeToLive = function () {
  157. return this.meta.time_to_live || 0;
  158. };
  159. /**
  160. * is burn-after-reading enabled
  161. *
  162. * @name Paste.isBurnAfterReadingEnabled
  163. * @function
  164. * @return {bool}
  165. */
  166. this.isBurnAfterReadingEnabled = function () {
  167. return this.adata[3];
  168. };
  169. /**
  170. * are discussions enabled
  171. *
  172. * @name Paste.isDiscussionEnabled
  173. * @function
  174. * @return {bool}
  175. */
  176. this.isDiscussionEnabled = function () {
  177. return this.adata[2];
  178. };
  179. }
  180. /**
  181. * Comment class
  182. *
  183. * bundles helper functions around the comment formats
  184. *
  185. * @name Comment
  186. * @class
  187. */
  188. function Comment(data) {
  189. // inherit constructor and methods of CryptoData
  190. CryptoData.call(this, data);
  191. /**
  192. * gets the UNIX timestamp of the comment creation
  193. *
  194. * @name Comment.getCreated
  195. * @function
  196. * @return {int}
  197. */
  198. this.getCreated = function () {
  199. return this.meta.created || 0;
  200. };
  201. /**
  202. * gets the icon of the comment submitter
  203. *
  204. * @name Comment.getIcon
  205. * @function
  206. * @return {string}
  207. */
  208. this.getIcon = function () {
  209. return this.meta.icon || '';
  210. };
  211. /**
  212. * checks if the comment belongs to the given document and its parent
  213. *
  214. * Comments without authenticated IDs predate this check and are
  215. * accepted.
  216. *
  217. * @name Comment.isBoundTo
  218. * @function
  219. * @param {string} pasteId
  220. * @return {bool}
  221. */
  222. this.isBoundTo = function (pasteId) {
  223. return this.adata.length === 8 || (
  224. this.adata.length === 10 &&
  225. this.adata[8] === pasteId &&
  226. this.adata[9] === this.parentid
  227. );
  228. };
  229. }
  230. /**
  231. * static Helper methods
  232. *
  233. * @name Helper
  234. * @class
  235. */
  236. const Helper = (function () {
  237. const me = {};
  238. /**
  239. * character to HTML entity lookup table
  240. *
  241. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  242. * @name Helper.entityMap
  243. * @private
  244. * @enum {Object}
  245. * @readonly
  246. */
  247. const entityMap = {
  248. '&': '&',
  249. '<': '&lt;',
  250. '>': '&gt;',
  251. '"': '&quot;',
  252. '\'': '&#39;',
  253. '/': '&#x2F;',
  254. '`': '&#x60;',
  255. '=': '&#x3D;'
  256. };
  257. /**
  258. * number of seconds in a minute
  259. *
  260. * @name Helper.minute
  261. * @private
  262. * @enum {number}
  263. * @readonly
  264. */
  265. const minute = 60;
  266. /**
  267. * number of seconds in an hour
  268. *
  269. * = 60 * 60 seconds
  270. *
  271. * @name Helper.minute
  272. * @private
  273. * @enum {number}
  274. * @readonly
  275. */
  276. const hour = 3600;
  277. /**
  278. * number of seconds in a day
  279. *
  280. * = 60 * 60 * 24 seconds
  281. *
  282. * @name Helper.day
  283. * @private
  284. * @enum {number}
  285. * @readonly
  286. */
  287. const day = 86400;
  288. /**
  289. * number of seconds in a week
  290. *
  291. * = 60 * 60 * 24 * 7 seconds
  292. *
  293. * @name Helper.week
  294. * @private
  295. * @enum {number}
  296. * @readonly
  297. */
  298. const week = 604800;
  299. /**
  300. * number of seconds in a month (30 days, an approximation)
  301. *
  302. * = 60 * 60 * 24 * 30 seconds
  303. *
  304. * @name Helper.month
  305. * @private
  306. * @enum {number}
  307. * @readonly
  308. */
  309. const month = 2592000;
  310. /**
  311. * number of seconds in a non-leap year
  312. *
  313. * = 60 * 60 * 24 * 365 seconds
  314. *
  315. * @name Helper.year
  316. * @private
  317. * @enum {number}
  318. * @readonly
  319. */
  320. const year = 31536000;
  321. /**
  322. * cache for script location
  323. *
  324. * @name Helper.baseUri
  325. * @private
  326. * @enum {string|null}
  327. */
  328. let baseUri = null;
  329. /**
  330. * converts a duration (in seconds) into human friendly approximation
  331. *
  332. * @name Helper.secondsToHuman
  333. * @function
  334. * @param {number} seconds
  335. * @return {Array}
  336. */
  337. me.secondsToHuman = function (seconds) {
  338. let v;
  339. if (seconds < minute) {
  340. v = Math.floor(seconds);
  341. return [v, 'second'];
  342. }
  343. if (seconds < hour) {
  344. v = Math.floor(seconds / minute);
  345. return [v, 'minute'];
  346. }
  347. if (seconds < day) {
  348. v = Math.floor(seconds / hour);
  349. return [v, 'hour'];
  350. }
  351. // If less than 2 months, display in days:
  352. if (seconds <= (2 * month)) {
  353. v = Math.floor(seconds / day);
  354. return [v, 'day'];
  355. }
  356. v = Math.floor(seconds / month);
  357. return [v, 'month'];
  358. };
  359. /**
  360. * converts a duration string into seconds
  361. *
  362. * The string is expected to be optional digits, followed by a time.
  363. * Supported times are: min, hour, day, month, year, never
  364. * Examples: 5min, 13hour, never
  365. *
  366. * @name Helper.durationToSeconds
  367. * @function
  368. * @param {String} duration
  369. * @return {number}
  370. */
  371. me.durationToSeconds = function (duration) {
  372. let pieces = duration.split(/(\D+)/),
  373. factor = pieces[0] || 0,
  374. timespan = pieces[1] || pieces[0];
  375. switch (timespan) {
  376. case 'min':
  377. return factor * minute;
  378. case 'hour':
  379. return factor * hour;
  380. case 'day':
  381. return factor * day;
  382. case 'week':
  383. return factor * week;
  384. case 'month':
  385. return factor * month;
  386. case 'year':
  387. return factor * year;
  388. case 'never':
  389. return 0;
  390. default:
  391. return factor;
  392. }
  393. };
  394. /**
  395. * text range selection
  396. *
  397. * @name Helper.selectText
  398. * @function
  399. * @param {HTMLElement} element
  400. */
  401. me.selectText = function (element) {
  402. let range, selection;
  403. if (window.getSelection) {
  404. selection = window.getSelection();
  405. if (!selection) {
  406. console.warn('window.getSelection() returned null, could not get any select text');
  407. return;
  408. }
  409. range = document.createRange();
  410. range.selectNodeContents(element);
  411. selection.removeAllRanges();
  412. selection.addRange(range);
  413. }
  414. };
  415. /**
  416. * convert URLs to clickable links in the provided element.
  417. *
  418. * URLs to handle:
  419. * <pre>
  420. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  421. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  422. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  423. * </pre>
  424. *
  425. * @name Helper.urls2links
  426. * @function
  427. * @param {HTMLElement} element
  428. * @param {Boolean} strict - optional
  429. */
  430. me.urls2links = function (element, strict = true) {
  431. const raw = element.innerHTML;
  432. element.innerHTML = DOMPurify.sanitize(
  433. raw.replace(
  434. /(((https?|ftp):\/\/[\w?!=&.\/;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]>))|((magnet):[\w?=&.\/;#@~%+*-]+))/ig,
  435. '<a href="$1">$1</a>'
  436. ),
  437. strict ? purifyHtmlConfigStrictSubset : purifyHtmlConfig
  438. );
  439. element.querySelectorAll('a').forEach(function (link) {
  440. const href = link.getAttribute('href');
  441. if (href && href.match(/^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i)) {
  442. link.setAttribute('target', '_blank');
  443. link.setAttribute('rel', 'nofollow noopener noreferrer');
  444. }
  445. });
  446. };
  447. /**
  448. * minimal sprintf emulation for %s and %d formats
  449. *
  450. * Note that this function needs the parameters in the same order as the
  451. * format strings appear in the string, contrary to the original.
  452. *
  453. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  454. * @name Helper.sprintf
  455. * @function
  456. * @param {string} format
  457. * @param {...*} args - one or multiple parameters injected into format string
  458. * @return {string}
  459. */
  460. me.sprintf = function () {
  461. const args = Array.prototype.slice.call(arguments);
  462. let format = args[0],
  463. i = 1;
  464. return format.replace(/%(s|d)/g, function (m) {
  465. let val = args[i];
  466. if (m === '%d') {
  467. val = parseFloat(val);
  468. if (isNaN(val)) {
  469. val = 0;
  470. }
  471. }
  472. ++i;
  473. return val;
  474. });
  475. };
  476. /**
  477. * get value of cookie, if it was set, empty string otherwise
  478. *
  479. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  480. * @name Helper.getCookie
  481. * @function
  482. * @param {string} cname - may not be empty
  483. * @return {string}
  484. */
  485. me.getCookie = function (cname) {
  486. const name = cname + '=',
  487. ca = document.cookie.split(';');
  488. for (let i = 0; i < ca.length; ++i) {
  489. let c = ca[i].trim();
  490. if (c.startsWith(name))
  491. {
  492. return c.substring(name.length, c.length);
  493. }
  494. }
  495. return '';
  496. };
  497. /**
  498. * get the current location (without search or hash part of the URL),
  499. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  500. *
  501. * @name Helper.baseUri
  502. * @function
  503. * @return {string}
  504. */
  505. me.baseUri = function () {
  506. // check for cached version
  507. if (baseUri !== null) {
  508. return baseUri;
  509. }
  510. baseUri = window.location.origin + window.location.pathname;
  511. return baseUri;
  512. };
  513. /**
  514. * wrap an object into a Paste, used for mocking in the unit tests
  515. *
  516. * @name Helper.PasteFactory
  517. * @function
  518. * @param {object} data
  519. * @return {Paste}
  520. */
  521. me.PasteFactory = function (data) {
  522. return new Paste(data);
  523. };
  524. /**
  525. * wrap an object into a Comment, used for mocking in the unit tests
  526. *
  527. * @name Helper.CommentFactory
  528. * @function
  529. * @param {object} data
  530. * @return {Comment}
  531. */
  532. me.CommentFactory = function (data) {
  533. return new Comment(data);
  534. };
  535. /**
  536. * convert all applicable characters to HTML entities
  537. *
  538. * @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html}
  539. * @name Helper.htmlEntities
  540. * @function
  541. * @param {string} str
  542. * @return {string} escaped HTML
  543. */
  544. me.htmlEntities = function (str) {
  545. return String(str).replace(
  546. /[&<>"'`=\/]/g, function (s) {
  547. return entityMap[s];
  548. }
  549. );
  550. };
  551. /**
  552. * calculate expiration date given initial date and expiration period
  553. *
  554. * @name Helper.calculateExpirationDate
  555. * @function
  556. * @param {Date} initialDate - may not be empty
  557. * @param {string|number} expirationDisplayStringOrSecondsToExpire - may not be empty
  558. * @return {Date}
  559. */
  560. me.calculateExpirationDate = function (initialDate, expirationDisplayStringOrSecondsToExpire) {
  561. let expirationDate = new Date(initialDate),
  562. secondsToExpiration = expirationDisplayStringOrSecondsToExpire;
  563. if (typeof expirationDisplayStringOrSecondsToExpire === 'string') {
  564. secondsToExpiration = me.durationToSeconds(expirationDisplayStringOrSecondsToExpire);
  565. }
  566. if (typeof secondsToExpiration !== 'number') {
  567. throw new Error('Cannot calculate expiration date.');
  568. }
  569. if (secondsToExpiration === 0) {
  570. return null;
  571. }
  572. expirationDate = expirationDate.setUTCSeconds(expirationDate.getUTCSeconds() + secondsToExpiration);
  573. return expirationDate;
  574. };
  575. /**
  576. * Convert Bytes to kB/MB/GB/TB/PB/EB/ZB/YB
  577. *
  578. * @name Helper.formatBytes
  579. * @function
  580. *
  581. * @param {number} bytes
  582. * @return {string}
  583. */
  584. me.formatBytes = function (bytes) {
  585. let result = '';
  586. const kilobyte = 1000;
  587. const decimalPoint = 2;
  588. const sizes = [
  589. I18n._('B'), I18n._('kB'), I18n._('MB'), I18n._('GB'), I18n._('TB'),
  590. I18n._('PB'), I18n._('EB'), I18n._('ZB'), I18n._('YB')
  591. ];
  592. const index = Math.floor(Math.log(bytes) / Math.log(kilobyte));
  593. if (bytes > 0) {
  594. result = parseFloat((bytes / Math.pow(kilobyte, index)).toFixed(decimalPoint)) + ' ' + sizes[index];
  595. } else {
  596. result = `0 ${I18n._('B')}`;
  597. }
  598. return result;
  599. };
  600. /**
  601. * resets state, used for unit testing
  602. *
  603. * @name Helper.reset
  604. * @function
  605. */
  606. me.reset = function () {
  607. baseUri = null;
  608. };
  609. /**
  610. * check if bootstrap5 object detected
  611. *
  612. * @name Helper.isBootstrap5
  613. * @returns {Boolean}
  614. */
  615. me.isBootstrap5 = function () {
  616. return typeof bootstrap !== 'undefined';
  617. };
  618. return me;
  619. })();
  620. /**
  621. * internationalization module
  622. *
  623. * @name I18n
  624. * @class
  625. */
  626. const I18n = (function () {
  627. const me = {};
  628. /**
  629. * const for string of loaded language
  630. *
  631. * @name I18n.languageLoadedEvent
  632. * @private
  633. * @prop {string}
  634. * @readonly
  635. */
  636. const languageLoadedEvent = 'languageLoaded';
  637. /**
  638. * supported languages, minus the built in 'en'
  639. *
  640. * @name I18n.supportedLanguages
  641. * @private
  642. * @prop {string[]}
  643. * @readonly
  644. */
  645. const supportedLanguages = ['ar', 'bg', 'ca', 'co', 'cs', 'de', 'el', 'es', 'et', 'fa', 'fi', 'fr', 'he', 'hu', 'id', 'it', 'ja', 'jbo', 'ko', 'lt', 'no', 'nl', 'pl', 'pt', 'oc', 'ro', 'ru', 'sk', 'sl', 'sv', 'th', 'tr', 'uk', 'zh', 'zh-tw'];
  646. /**
  647. * built in language
  648. *
  649. * @name I18n.language
  650. * @private
  651. * @prop {string|null}
  652. */
  653. let language = null;
  654. /**
  655. * translation cache
  656. *
  657. * @name I18n.translations
  658. * @private
  659. * @enum {Object}
  660. */
  661. let translations = Object.create(null);
  662. /**
  663. * translate a string, alias for I18n.translate
  664. *
  665. * @name I18n._
  666. * @function
  667. * @param {HTMLElement} element - optional
  668. * @param {string} messageId
  669. * @param {...*} args - one or multiple parameters injected into placeholders
  670. * @return {string}
  671. */
  672. me._ = function () {
  673. return me.translate.apply(this, arguments);
  674. };
  675. /**
  676. * translate a string
  677. *
  678. * Optionally pass an HTMLElement as the first parameter, to automatically
  679. * let the text of this element be replaced. In case the (asynchronously
  680. * loaded) language is not downloaded yet, this will make sure the string
  681. * is replaced when it eventually gets loaded. Using this is both simpler
  682. * and more secure, as it avoids potential XSS when inserting text.
  683. * The next parameter is the message ID, matching the ones found in
  684. * the translation files under the i18n directory.
  685. * Any additional parameters will get inserted into the message ID in
  686. * place of %s (strings) or %d (digits), applying the appropriate plural
  687. * in case of digits. See also Helper.sprintf().
  688. *
  689. * @name I18n.translate
  690. * @function
  691. * @param {HTMLElement} element - optional
  692. * @param {string} messageId
  693. * @param {...*} args - one or multiple parameters injected into placeholders
  694. * @return {string}
  695. */
  696. me.translate = function () // eslint-disable-line complexity
  697. {
  698. // convert parameters to array
  699. let args = Array.prototype.slice.call(arguments),
  700. messageId,
  701. element = null;
  702. // parse arguments
  703. if (args[0] === null || args[0] instanceof HTMLElement) {
  704. // optional HTMLElement as first parameter (null means element not found)
  705. element = args[0];
  706. args.shift();
  707. }
  708. // extract messageId from arguments
  709. let usesPlurals = Array.isArray(args[0]);
  710. if (usesPlurals) {
  711. // use the first plural form as messageId, otherwise the singular
  712. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  713. } else {
  714. messageId = args[0];
  715. }
  716. if (messageId.length === 0) {
  717. return messageId;
  718. }
  719. // if no translation string cannot be found (in translations object)
  720. if (!Object.prototype.hasOwnProperty.call(translations, messageId) || language === null) {
  721. // if language is still loading and we have an element assigned
  722. if (language === null && element !== null) {
  723. // handle the error by attaching the language loaded event
  724. let orgArguments = arguments;
  725. document.addEventListener(languageLoadedEvent, function () {
  726. // re-execute this function
  727. me.translate.apply(this, orgArguments);
  728. });
  729. // and fall back to English for now until the real language
  730. // file is loaded
  731. }
  732. // for all other languages than English for which this behaviour
  733. // is expected as it is built-in, log error
  734. if (language !== null && language !== 'en') {
  735. console.error('Missing translation for: ', messageId, 'in language', language);
  736. // fallback to English
  737. }
  738. // save English translation (should be the same on both sides)
  739. translations[messageId] = args[0];
  740. }
  741. // lookup plural translation
  742. if (usesPlurals && Array.isArray(translations[messageId])) {
  743. let n = parseInt(args[1] || 1, 10),
  744. key = me.getPluralForm(n),
  745. maxKey = translations[messageId].length - 1;
  746. if (key > maxKey) {
  747. key = maxKey;
  748. }
  749. args[0] = translations[messageId][key];
  750. args[1] = n;
  751. } else {
  752. // lookup singular translation
  753. args[0] = translations[messageId];
  754. }
  755. // messageID may contain HTML, but should be from a trusted source (code or translation JSON files)
  756. let containsHtml = isStringContainsHtml(args[0]);
  757. // prevent double encoding, when we insert into a text node
  758. if (containsHtml || element === null) {
  759. for (let i = 0; i < args.length; ++i) {
  760. // parameters (i > 0) may never contain HTML as they may come from untrusted parties
  761. if ((containsHtml ? i > 1 : i > 0) || !containsHtml) {
  762. args[i] = Helper.htmlEntities(args[i]);
  763. }
  764. }
  765. }
  766. // format string
  767. let output = Helper.sprintf.apply(this, args);
  768. if (containsHtml) {
  769. // only allow tags/attributes we actually use in translations
  770. output = DOMPurify.sanitize(output, purifyTranslationConfig);
  771. }
  772. // if element is given, insert translation
  773. if (element !== null) {
  774. if (containsHtml) {
  775. element.innerHTML = output;
  776. } else {
  777. // text node takes care of entity encoding
  778. element.textContent = output;
  779. }
  780. return '';
  781. }
  782. return output;
  783. };
  784. /**
  785. * get currently loaded language
  786. *
  787. * @name I18n.getLanguage
  788. * @function
  789. * @return {string}
  790. */
  791. me.getLanguage = function () {
  792. return language;
  793. };
  794. /**
  795. * per language functions to use to determine the plural form
  796. *
  797. * @see {@link https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html}
  798. * @name I18n.getPluralForm
  799. * @function
  800. * @param {int} n
  801. * @return {int} array key
  802. */
  803. me.getPluralForm = function (n) { // eslint-disable-line complexity
  804. switch (language) {
  805. case 'ar':
  806. return n === 0 ? 0 : (n === 1 ? 1 : (n === 2 ? 2 : (n % 100 >= 3 && n % 100 <= 10 ? 3 : (n % 100 >= 11 ? 4 : 5))));
  807. case 'cs':
  808. case 'sk':
  809. return n === 1 ? 0 : (n >= 2 && n <= 4 ? 1 : 2);
  810. case 'co':
  811. case 'fa':
  812. case 'fr':
  813. case 'oc':
  814. case 'tr':
  815. case 'zh':
  816. case 'zh-tw':
  817. return n > 1 ? 1 : 0;
  818. case 'he':
  819. return n === 1 ? 0 : (n === 2 ? 1 : ((n < 0 || n > 10) && (n % 10 === 0) ? 2 : 3));
  820. case 'id':
  821. case 'ja':
  822. case 'jbo':
  823. case 'ko':
  824. case 'th':
  825. return 0;
  826. case 'lt':
  827. return n % 10 === 1 && n % 100 !== 11 ? 0 : ((n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20)) ? 1 : 2);
  828. case 'pl':
  829. return n === 1 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  830. case 'ro':
  831. return n === 1 ? 0 : ((n === 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2);
  832. case 'ru':
  833. case 'uk':
  834. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  835. case 'sl':
  836. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  837. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt, sv
  838. default:
  839. return n !== 1 ? 1 : 0;
  840. }
  841. };
  842. /**
  843. * load translations into cache
  844. *
  845. * @name I18n.loadTranslations
  846. * @function
  847. */
  848. me.loadTranslations = function () {
  849. let newLanguage = Helper.getCookie('lang');
  850. // auto-select language based on browser settings
  851. if (newLanguage.length === 0) {
  852. newLanguage = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
  853. const isTraditionalChinese = newLanguage.startsWith('zh-tw-') ||
  854. newLanguage === 'zh-hant' || newLanguage.startsWith('zh-hant-') ||
  855. newLanguage === 'zh-hk' || newLanguage.startsWith('zh-hk-') ||
  856. newLanguage === 'zh-mo' || newLanguage.startsWith('zh-mo-');
  857. // alias Traditional Chinese browser tags to PrivateBin's zh-tw locale;
  858. // otherwise try the full tag and fall back to the base language
  859. if (isTraditionalChinese && supportedLanguages.includes('zh-tw')) {
  860. newLanguage = 'zh-tw';
  861. } else if (!supportedLanguages.includes(newLanguage) && newLanguage.includes('-')) {
  862. newLanguage = newLanguage.split('-')[0];
  863. }
  864. }
  865. // if language is already used skip update
  866. if (newLanguage === language) {
  867. return;
  868. }
  869. // if language is built-in (English) skip update
  870. if (newLanguage === 'en') {
  871. language = 'en';
  872. return;
  873. }
  874. // if language is not supported, show error
  875. if (!supportedLanguages.includes(newLanguage)) {
  876. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  877. language = 'en';
  878. return;
  879. }
  880. // load strings from JSON
  881. const scriptTag = document.querySelector('script[src^="js/privatebin.js"]');
  882. const cacheBreaker = scriptTag ? (scriptTag.getAttribute('src').split('.js')[1] || '') : '';
  883. fetch('i18n/' + newLanguage + '.json' + cacheBreaker)
  884. .then(response => {
  885. if (!response.ok) {
  886. throw new Error('HTTP ' + response.status + ' ' + response.statusText);
  887. }
  888. return response.json();
  889. })
  890. .then(data => {
  891. language = newLanguage;
  892. translations = Object.assign(Object.create(null), data);
  893. document.dispatchEvent(new CustomEvent(languageLoadedEvent));
  894. })
  895. .catch(error => {
  896. console.error(`Language \'${newLanguage}\' could not be loaded (${error.message}). Translation failed, fallback to English.`);
  897. language = 'en';
  898. });
  899. };
  900. /**
  901. * Register a callback to be invoked when translations have been loaded.
  902. *
  903. * This is useful for code that needs to re-apply translated strings to
  904. * DOM attributes (e.g. title attributes) that cannot be handled by
  905. * I18n.translate's built-in element re-translation mechanism (which only
  906. * sets textContent/innerHTML).
  907. *
  908. * Note: If translations are already loaded when this is called, the
  909. * callback will not be invoked. Callers should apply the translation
  910. * immediately as well, to cover the case where the language is already
  911. * available.
  912. *
  913. * @name I18n.onLanguageLoaded
  914. * @function
  915. * @param {function} callback - function to call when language is loaded
  916. */
  917. me.onLanguageLoaded = function (callback) {
  918. document.addEventListener(languageLoadedEvent, callback);
  919. };
  920. /**
  921. * resets state, used for unit testing
  922. *
  923. * @name I18n.reset
  924. * @function
  925. */
  926. me.reset = function (mockLanguage, mockTranslations) {
  927. language = mockLanguage || null;
  928. translations = mockTranslations || Object.create(null);
  929. };
  930. /**
  931. * Check if string contains valid HTML code.
  932. *
  933. * If it is no string at all, this always returns false for compatibility.
  934. *
  935. * @name I18n.isStringContainsHtml
  936. * @function
  937. * @private
  938. * @param {string|object} messageId
  939. * @returns {boolean}
  940. */
  941. function isStringContainsHtml(messageId) {
  942. // message IDs are allowed to contain anchors, spans, keyboard and emphasis tags
  943. // we can recognize all of them by only checking for anchors and keyboard tags
  944. return typeof messageId === 'string' && (messageId.includes('<a') || messageId.includes('<kbd'));
  945. }
  946. return me;
  947. })();
  948. /**
  949. * handles everything related to en/decryption
  950. *
  951. * @name CryptTool
  952. * @class
  953. */
  954. const CryptTool = (function () {
  955. const me = {};
  956. /**
  957. * base58 encoder & decoder
  958. *
  959. * @private
  960. */
  961. const base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  962. /**
  963. * convert ArrayBuffer into a UTF-8 string
  964. *
  965. * Iterates over the bytes of the array, catenating them into a string
  966. *
  967. * @name CryptTool.arraybufferToString
  968. * @function
  969. * @private
  970. * @param {ArrayBuffer} messageArray
  971. * @return {string} message
  972. */
  973. function arraybufferToString(messageArray)
  974. {
  975. return Array.from(new Uint8Array(messageArray))
  976. .map(byte => String.fromCharCode(byte))
  977. .join('');
  978. }
  979. /**
  980. * convert UTF-8 string into a Uint8Array
  981. *
  982. * Iterates over the bytes of the message, writing them to the array
  983. *
  984. * @name CryptTool.stringToArraybuffer
  985. * @function
  986. * @private
  987. * @param {string} message UTF-8 string
  988. * @return {Uint8Array} array
  989. */
  990. function stringToArraybuffer(message)
  991. {
  992. return Uint8Array.from(
  993. message,
  994. character => character.charCodeAt(0)
  995. );
  996. }
  997. /**
  998. * compress a string (deflate compression), returns buffer
  999. *
  1000. * @name CryptTool.compress
  1001. * @async
  1002. * @function
  1003. * @private
  1004. * @param {string} message
  1005. * @param {string} mode
  1006. * @param {object} zlib
  1007. * @throws {string}
  1008. * @return {ArrayBuffer} data
  1009. */
  1010. async function compress(message, mode, zlib) {
  1011. message = new TextEncoder().encode(message);
  1012. if (mode === 'zlib') {
  1013. if (typeof zlib === 'undefined') {
  1014. throw new Error('Error compressing document, due to missing WebAssembly support.');
  1015. }
  1016. return zlib.deflate(message).buffer;
  1017. }
  1018. return message;
  1019. }
  1020. /**
  1021. * decompress potentially base64 encoded, deflate compressed buffer, returns string
  1022. *
  1023. * @name CryptTool.decompress
  1024. * @async
  1025. * @function
  1026. * @private
  1027. * @param {ArrayBuffer} data
  1028. * @param {string} mode
  1029. * @param {object} zlib
  1030. * @throws {string}
  1031. * @return {string} message
  1032. */
  1033. async function decompress(data, mode, zlib) {
  1034. if (mode === 'zlib') {
  1035. if (typeof zlib === 'undefined') {
  1036. throw new Error('Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.');
  1037. }
  1038. data = zlib.inflate(
  1039. new Uint8Array(data)
  1040. ).buffer;
  1041. }
  1042. return new TextDecoder('utf-8', {fatal: true}).decode(data);
  1043. }
  1044. /**
  1045. * returns specified number of random bytes
  1046. *
  1047. * @name CryptTool.getRandomBytes
  1048. * @function
  1049. * @private
  1050. * @param {int} length number of random bytes to fetch
  1051. * @throws {string}
  1052. * @return {string} random bytes
  1053. */
  1054. function getRandomBytes(length) {
  1055. let bytes = '';
  1056. const byteArray = new Uint8Array(length);
  1057. window.crypto.getRandomValues(byteArray);
  1058. for (let i = 0; i < length; ++i) {
  1059. bytes += String.fromCharCode(byteArray[i]);
  1060. }
  1061. return bytes;
  1062. }
  1063. /**
  1064. * derive cryptographic key from key string and password
  1065. *
  1066. * @name CryptTool.deriveKey
  1067. * @async
  1068. * @function
  1069. * @private
  1070. * @param {string} key
  1071. * @param {string} password
  1072. * @param {array} spec cryptographic specification
  1073. * @return {CryptoKey} derived key
  1074. */
  1075. async function deriveKey(key, password, spec) {
  1076. let keyArray = stringToArraybuffer(key);
  1077. if (password.length > 0) {
  1078. let passwordArray = stringToArraybuffer(password),
  1079. newKeyArray = new Uint8Array(keyArray.length + passwordArray.length);
  1080. newKeyArray.set(keyArray, 0);
  1081. newKeyArray.set(passwordArray, keyArray.length);
  1082. keyArray = newKeyArray;
  1083. }
  1084. // import raw key
  1085. const importedKey = await window.crypto.subtle.importKey(
  1086. 'raw', // only 'raw' is allowed
  1087. keyArray,
  1088. { name: 'PBKDF2' }, // we use PBKDF2 for key derivation
  1089. false, // the key may not be exported
  1090. ['deriveKey'] // we may only use it for key derivation
  1091. ).catch(Alert.showError);
  1092. // derive a stronger key for use with AES
  1093. return window.crypto.subtle.deriveKey(
  1094. {
  1095. name: 'PBKDF2', // we use PBKDF2 for key derivation
  1096. salt: stringToArraybuffer(spec[1]), // salt used in HMAC
  1097. iterations: spec[2], // amount of iterations to apply
  1098. hash: { name: 'SHA-256' } // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  1099. },
  1100. importedKey,
  1101. {
  1102. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1103. length: spec[3] // can be 128, 192 or 256
  1104. },
  1105. false, // the key may not be exported
  1106. ['encrypt', 'decrypt'] // we may only use it for en- and decryption
  1107. ).catch(Alert.showError);
  1108. }
  1109. /**
  1110. * gets crypto settings from specification and authenticated data
  1111. *
  1112. * @name CryptTool.cryptoSettings
  1113. * @function
  1114. * @private
  1115. * @param {string} adata authenticated data
  1116. * @param {array} spec cryptographic specification
  1117. * @return {object} crypto settings
  1118. */
  1119. function cryptoSettings(adata, spec) {
  1120. return {
  1121. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1122. iv: stringToArraybuffer(spec[0]), // the initialization vector you used to encrypt
  1123. additionalData: stringToArraybuffer(adata), // the addtional data you used during encryption (if any)
  1124. tagLength: spec[4] // the length of the tag you used to encrypt (if any)
  1125. };
  1126. }
  1127. /**
  1128. * compress, then encrypt message with given key and password
  1129. *
  1130. * @name CryptTool.cipher
  1131. * @async
  1132. * @function
  1133. * @param {string} key
  1134. * @param {string} password
  1135. * @param {string} message
  1136. * @param {array} adata
  1137. * @return {array} encrypted message in base64 encoding & adata containing encryption spec
  1138. */
  1139. me.cipher = async function (key, password, message, adata) {
  1140. let zlib = (await z);
  1141. // AES in Galois Counter Mode, keysize 256 bit,
  1142. // authentication tag 128 bit, 10000 iterations in key derivation
  1143. const compression = (
  1144. typeof zlib === 'undefined' ?
  1145. 'none' : // client lacks support for WASM
  1146. (document.body.dataset.compression || 'zlib')
  1147. ),
  1148. spec = [
  1149. getRandomBytes(16), // initialization vector
  1150. getRandomBytes(8), // salt
  1151. 100000, // iterations
  1152. 256, // key size
  1153. 128, // tag size
  1154. 'aes', // algorithm
  1155. 'gcm', // algorithm mode
  1156. compression // compression
  1157. ], encodedSpec = [];
  1158. for (let i = 0; i < spec.length; ++i) {
  1159. encodedSpec[i] = i < 2 ? btoa(spec[i]) : spec[i];
  1160. }
  1161. if (adata[0] === null) {
  1162. // paste
  1163. adata[0] = encodedSpec;
  1164. } else {
  1165. // comment, optionally followed by its document and parent IDs
  1166. adata = encodedSpec.concat(adata);
  1167. }
  1168. // finally, encrypt message
  1169. return [
  1170. btoa(
  1171. arraybufferToString(
  1172. await window.crypto.subtle.encrypt(
  1173. cryptoSettings(JSON.stringify(adata), spec),
  1174. await deriveKey(key, password, spec),
  1175. await compress(message, compression, zlib)
  1176. ).catch(Alert.showError)
  1177. )
  1178. ),
  1179. adata
  1180. ];
  1181. };
  1182. /**
  1183. * decrypt message with key, then decompress
  1184. *
  1185. * @name CryptTool.decipher
  1186. * @async
  1187. * @function
  1188. * @param {string} key
  1189. * @param {string} password
  1190. * @param {string|object} data encrypted message
  1191. * @return {string} decrypted message, empty if decryption failed
  1192. */
  1193. me.decipher = async function (key, password, data) {
  1194. let adataString, spec, cipherMessage, plaintext;
  1195. let zlib = (await z);
  1196. if (data instanceof Array) {
  1197. // version 2
  1198. adataString = JSON.stringify(data[1]);
  1199. // clone the array instead of passing the reference
  1200. spec = (data[1][0] instanceof Array ? data[1][0] : data[1]).slice();
  1201. cipherMessage = data[0];
  1202. } else {
  1203. throw 'unsupported message format';
  1204. }
  1205. spec[0] = atob(spec[0]);
  1206. spec[1] = atob(spec[1]);
  1207. if (spec[7] === 'zlib') {
  1208. if (typeof zlib === 'undefined') {
  1209. throw 'Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.';
  1210. }
  1211. }
  1212. try {
  1213. plaintext = await window.crypto.subtle.decrypt(
  1214. cryptoSettings(adataString, spec),
  1215. await deriveKey(key, password, spec),
  1216. stringToArraybuffer(
  1217. atob(cipherMessage)
  1218. )
  1219. );
  1220. } catch (err) {
  1221. console.error(err);
  1222. return '';
  1223. }
  1224. try {
  1225. return await decompress(plaintext, spec[7], zlib);
  1226. } catch (err) {
  1227. Alert.showError(err);
  1228. return err;
  1229. }
  1230. };
  1231. /**
  1232. * returns a random symmetric key
  1233. *
  1234. * generates 256 bit long keys (8 Bits * 32) for AES with 256 bit long blocks
  1235. *
  1236. * @name CryptTool.getSymmetricKey
  1237. * @function
  1238. * @throws {string}
  1239. * @return {string} raw bytes
  1240. */
  1241. me.getSymmetricKey = function () {
  1242. return getRandomBytes(32);
  1243. };
  1244. /**
  1245. * base58 encode a DOMString (UTF-16)
  1246. *
  1247. * @name CryptTool.base58encode
  1248. * @function
  1249. * @param {string} input
  1250. * @return {string} output
  1251. */
  1252. me.base58encode = function (input) {
  1253. return base58.encode(
  1254. stringToArraybuffer(input)
  1255. );
  1256. };
  1257. /**
  1258. * base58 decode a DOMString (UTF-16)
  1259. *
  1260. * @name CryptTool.base58decode
  1261. * @function
  1262. * @param {string} input
  1263. * @return {string} output
  1264. */
  1265. me.base58decode = function (input) {
  1266. return arraybufferToString(
  1267. base58.decode(input)
  1268. );
  1269. };
  1270. return me;
  1271. })();
  1272. /**
  1273. * (Model) Data source (aka MVC)
  1274. *
  1275. * @name Model
  1276. * @class
  1277. */
  1278. const Model = (function () {
  1279. const me = {};
  1280. let id = null,
  1281. pasteData = null,
  1282. symmetricKey = null,
  1283. templates;
  1284. /**
  1285. * returns the expiration set in the HTML
  1286. *
  1287. * @name Model.getExpirationDefault
  1288. * @function
  1289. * @return string
  1290. */
  1291. me.getExpirationDefault = function () {
  1292. const element = document.getElementById('pasteExpiration');
  1293. return element ? element.value : '';
  1294. };
  1295. /**
  1296. * returns the format set in the HTML
  1297. *
  1298. * @name Model.getFormatDefault
  1299. * @function
  1300. * @return string
  1301. */
  1302. me.getFormatDefault = function () {
  1303. const element = document.getElementById('pasteFormatter');
  1304. return element ? element.value : '';
  1305. };
  1306. /**
  1307. * returns the document data (including the cipher data)
  1308. *
  1309. * @name Model.getPasteData
  1310. * @function
  1311. * @param {function} callback (optional) Called when data is available
  1312. * @param {function} useCache (optional) Whether to use the cache or
  1313. * force a data reload. Default: true
  1314. * @return string
  1315. */
  1316. me.getPasteData = function (callback, useCache) {
  1317. // use cache if possible/allowed
  1318. if (useCache !== false && pasteData !== null) {
  1319. //execute callback
  1320. if (typeof callback === 'function') {
  1321. return callback(pasteData);
  1322. }
  1323. // alternatively just using inline
  1324. return pasteData;
  1325. }
  1326. // reload data
  1327. ServerInteraction.prepare();
  1328. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + me.getPasteId());
  1329. ServerInteraction.setFailure(function (status, data) {
  1330. // revert loading status…
  1331. Alert.hideLoading();
  1332. TopNav.showViewButtons();
  1333. // show error message
  1334. Alert.showError(ServerInteraction.parseUploadError(status, data, 'get document data'));
  1335. });
  1336. ServerInteraction.setSuccess(function (status, data) {
  1337. pasteData = new Paste(data);
  1338. if (typeof callback === 'function') {
  1339. return callback(pasteData);
  1340. }
  1341. });
  1342. ServerInteraction.run();
  1343. };
  1344. /**
  1345. * get the documents unique identifier from the URL,
  1346. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  1347. *
  1348. * @name Model.getPasteId
  1349. * @function
  1350. * @return {string} unique identifier
  1351. * @throws {string}
  1352. */
  1353. me.getPasteId = function () {
  1354. const idRegEx = /^[a-f0-9]{16}$/;
  1355. // return cached value
  1356. if (id !== null) {
  1357. return id;
  1358. }
  1359. // do use URL interface, if possible
  1360. const url = new URL(window.location);
  1361. for (const param of url.searchParams) {
  1362. const key = param[0];
  1363. const value = param[1];
  1364. if (value === '' && idRegEx.test(key)) {
  1365. // safe, as the whole regex is matched
  1366. id = key;
  1367. return key;
  1368. }
  1369. }
  1370. if (id === null) {
  1371. throw 'no document id given';
  1372. }
  1373. return id;
  1374. };
  1375. /**
  1376. * returns true, when the URL has a delete token and the current call was used for deleting a document.
  1377. *
  1378. * @name Model.hasDeleteToken
  1379. * @function
  1380. * @return {bool}
  1381. */
  1382. me.hasDeleteToken = function () {
  1383. return (new URL(window.location)).searchParams.has('deletetoken');
  1384. };
  1385. /**
  1386. * return the deciphering key stored in anchor part of the URL
  1387. *
  1388. * @name Model.getPasteKey
  1389. * @function
  1390. * @return {string|null} key
  1391. * @throws {string}
  1392. */
  1393. me.getPasteKey = function () {
  1394. if (symmetricKey === null) {
  1395. let startPos = 1;
  1396. if (window.location.hash.startsWith(loadConfirmPrefix)) {
  1397. startPos = loadConfirmPrefix.length;
  1398. }
  1399. let newKey = window.location.hash.substring(startPos);
  1400. // Some web 2.0 services and redirectors add data AFTER the anchor
  1401. // (such as &utm_source=...). We will strip any additional data.
  1402. let ampersandPos = newKey.indexOf('&');
  1403. if (ampersandPos > -1) {
  1404. newKey = newKey.substring(0, ampersandPos);
  1405. }
  1406. if (newKey === '') {
  1407. throw 'no encryption key given';
  1408. }
  1409. // version 2 uses base58, version 1 uses base64 without decoding
  1410. try {
  1411. // base58 encode strips NULL bytes at the beginning of the
  1412. // string, so we re-add them if necessary
  1413. symmetricKey = CryptTool.base58decode(newKey).padStart(32, '\u0000');
  1414. } catch (e) {
  1415. throw 'encryption key of unsupported format given or incomplete, mangled URL';
  1416. }
  1417. }
  1418. return symmetricKey;
  1419. };
  1420. /**
  1421. * returns a copy of the HTML template
  1422. *
  1423. * @name Model.getTemplate
  1424. * @function
  1425. * @param {string} name - the name of the template
  1426. * @return {HTMLElement}
  1427. */
  1428. me.getTemplate = function (name) {
  1429. // find template
  1430. const template = document.getElementById(name + 'template');
  1431. if (!template || !templates.contains(template)) {
  1432. return null;
  1433. }
  1434. let element = template.cloneNode(true);
  1435. // change ID to avoid collisions (one ID should really be unique)
  1436. element.id = name;
  1437. return element;
  1438. };
  1439. /**
  1440. * resets state, used for unit testing
  1441. *
  1442. * @name Model.reset
  1443. * @function
  1444. */
  1445. me.reset = function () {
  1446. pasteData = templates = id = symmetricKey = null;
  1447. };
  1448. /**
  1449. * init navigation manager
  1450. *
  1451. * preloads elements
  1452. *
  1453. * @name Model.init
  1454. * @function
  1455. */
  1456. me.init = function () {
  1457. templates = document.getElementById('templates');
  1458. };
  1459. return me;
  1460. })();
  1461. /**
  1462. * Helper functions for user interface
  1463. *
  1464. * everything directly UI-related, which fits nowhere else
  1465. *
  1466. * @name UiHelper
  1467. * @class
  1468. */
  1469. const UiHelper = (function () {
  1470. const me = {};
  1471. /**
  1472. * handle history (pop) state changes
  1473. *
  1474. * currently this does only handle redirects to the home page.
  1475. *
  1476. * @name UiHelper.historyChange
  1477. * @private
  1478. * @function
  1479. * @param {PopStateEvent} event
  1480. */
  1481. function historyChange(event) {
  1482. let currentLocation = Helper.baseUri();
  1483. if (event.state === null && // no state object passed
  1484. event.target.location.href === currentLocation && // target location is home page
  1485. window.location.href === currentLocation // and we are not already on the home page
  1486. ) {
  1487. // redirect to home page
  1488. window.location.href = currentLocation;
  1489. }
  1490. }
  1491. /**
  1492. * reload the page
  1493. *
  1494. * This takes the user to the PrivateBin homepage.
  1495. *
  1496. * @name UiHelper.reloadHome
  1497. * @function
  1498. */
  1499. me.reloadHome = function () {
  1500. window.location.href = Helper.baseUri();
  1501. };
  1502. /**
  1503. * initialize
  1504. *
  1505. * @name UiHelper.init
  1506. * @function
  1507. */
  1508. me.init = function () {
  1509. // update link to home page
  1510. document.querySelectorAll('.reloadlink').forEach(link => (link.href = Helper.baseUri()));
  1511. window.addEventListener('popstate', historyChange);
  1512. };
  1513. return me;
  1514. })();
  1515. /**
  1516. * Alert/error manager
  1517. *
  1518. * @name Alert
  1519. * @class
  1520. */
  1521. const Alert = (function () {
  1522. const me = {};
  1523. let errorMessage,
  1524. loadingIndicator,
  1525. statusMessage,
  1526. remainingTime,
  1527. currentIcon,
  1528. customHandler;
  1529. const alertType = [
  1530. 'loading', // not in bootstrap CSS, but using a plausible value here
  1531. 'info', // status icon
  1532. 'warning', // warning icon
  1533. 'danger' // error icon
  1534. ];
  1535. /**
  1536. * forwards a request to the i18n module and shows the element
  1537. *
  1538. * @name Alert.handleNotification
  1539. * @private
  1540. * @function
  1541. * @param {number} id - id of notification
  1542. * @param {HTMLElement} element - HTML element
  1543. * @param {string|array} args
  1544. * @param {string|null} icon - optional, icon
  1545. */
  1546. function handleNotification(id, element, args, icon) {
  1547. // basic parsing/conversion of parameters
  1548. if (typeof icon === 'undefined') {
  1549. icon = null;
  1550. }
  1551. if (typeof args === 'undefined') {
  1552. args = null;
  1553. } else if (typeof args === 'string') {
  1554. // convert string to array if needed
  1555. args = [args];
  1556. } else if (args instanceof Error) {
  1557. // extract message into array if needed
  1558. args = [args.message];
  1559. }
  1560. // function guard
  1561. if (!element) {
  1562. throw new TypeError(`invalid/no element (${element}) given for alert type ${alertType[id]} with ID ${id}`);
  1563. }
  1564. // pass to custom handler if defined
  1565. if (typeof customHandler === 'function') {
  1566. let handlerResult = customHandler(alertType[id], element, args, icon);
  1567. if (handlerResult === true) {
  1568. // if it returns true, skip own handler
  1569. return;
  1570. }
  1571. if (handlerResult instanceof HTMLElement) {
  1572. // continue processing with new element
  1573. element = handlerResult;
  1574. icon = null; // icons not supported in this case
  1575. }
  1576. }
  1577. let translationTarget = element;
  1578. // handle icon, if template uses one
  1579. const glyphIcon = element.querySelector(':first-child');
  1580. if (glyphIcon) {
  1581. // if there is an icon, we need to provide an inner element
  1582. // to translate the message into, instead of the parent
  1583. translationTarget = document.createElement('span');
  1584. element.innerHTML = ' ';
  1585. element.prepend(glyphIcon);
  1586. element.appendChild(translationTarget);
  1587. if (icon !== null && // icon was passed
  1588. icon !== currentIcon[id] // and it differs from current icon
  1589. ) {
  1590. // remove (previous) icon
  1591. glyphIcon.classList.remove(currentIcon[id]);
  1592. // any other thing as a string (e.g. 'null') (only) removes the icon
  1593. if (typeof icon === 'string') {
  1594. // set new icon
  1595. currentIcon[id] = 'glyphicon-' + icon;
  1596. glyphIcon.classList.add(currentIcon[id]);
  1597. }
  1598. }
  1599. }
  1600. // translate and insert message
  1601. I18n._(translationTarget, ...args);
  1602. // show element
  1603. element.classList.remove('hidden');
  1604. }
  1605. /**
  1606. * display a status message
  1607. *
  1608. * This automatically passes the text to I18n for translation.
  1609. *
  1610. * @name Alert.showStatus
  1611. * @function
  1612. * @param {string|array} message string, use an array for %s/%d options
  1613. * @param {string|null} icon optional, the icon to show,
  1614. * default: leave previous icon
  1615. */
  1616. me.showStatus = function (message, icon) {
  1617. handleNotification(1, statusMessage, message, icon);
  1618. };
  1619. /**
  1620. * display a warning message
  1621. *
  1622. * This automatically passes the text to I18n for translation.
  1623. *
  1624. * @name Alert.showWarning
  1625. * @function
  1626. * @param {string|array} message string, use an array for %s/%d options
  1627. * @param {string|null} icon optional, the icon to show, default:
  1628. * leave previous icon
  1629. */
  1630. me.showWarning = function (message, icon) {
  1631. const glyphIcon = errorMessage.querySelector(':first-child');
  1632. if (glyphIcon) {
  1633. glyphIcon.classList.remove(currentIcon[3]);
  1634. glyphIcon.classList.add(currentIcon[2]);
  1635. }
  1636. handleNotification(2, errorMessage, message, icon);
  1637. };
  1638. /**
  1639. * display an error message
  1640. *
  1641. * This automatically passes the text to I18n for translation.
  1642. *
  1643. * @name Alert.showError
  1644. * @function
  1645. * @param {string|array} message string, use an array for %s/%d options
  1646. * @param {string|null} icon optional, the icon to show, default:
  1647. * leave previous icon
  1648. */
  1649. me.showError = function (message, icon) {
  1650. handleNotification(3, errorMessage, message, icon);
  1651. };
  1652. /**
  1653. * display remaining message
  1654. *
  1655. * This automatically passes the text to I18n for translation.
  1656. *
  1657. * @name Alert.showRemaining
  1658. * @function
  1659. * @param {string|array} message string, use an array for %s/%d options
  1660. */
  1661. me.showRemaining = function (message) {
  1662. handleNotification(1, remainingTime, message);
  1663. };
  1664. /**
  1665. * shows a loading message, optionally with a percentage
  1666. *
  1667. * This automatically passes all texts to the i10s module.
  1668. *
  1669. * @name Alert.showLoading
  1670. * @function
  1671. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1672. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1673. */
  1674. me.showLoading = function (message, icon) {
  1675. // default message text
  1676. if (typeof message === 'undefined') {
  1677. message = 'Loading…';
  1678. }
  1679. handleNotification(0, loadingIndicator, message, icon);
  1680. // show loading status (cursor)
  1681. document.body.classList.add('loading');
  1682. };
  1683. /**
  1684. * hides the loading message
  1685. *
  1686. * @name Alert.hideLoading
  1687. * @function
  1688. */
  1689. me.hideLoading = function () {
  1690. loadingIndicator.classList.add('hidden');
  1691. // hide loading cursor
  1692. document.body.classList.remove('loading');
  1693. };
  1694. /**
  1695. * hides any status/error messages
  1696. *
  1697. * This does not include the loading message.
  1698. *
  1699. * @name Alert.hideMessages
  1700. * @function
  1701. */
  1702. me.hideMessages = function () {
  1703. statusMessage.classList.add('hidden');
  1704. errorMessage.classList.add('hidden');
  1705. };
  1706. /**
  1707. * set a custom handler, which gets all notifications.
  1708. *
  1709. * This handler gets the following arguments:
  1710. * alertType (see array), $element, args, icon
  1711. * If it returns true, the own processing will be stopped so the message
  1712. * will not be displayed. Otherwise it will continue.
  1713. * As an aditional feature it can return a HTMLElement, which will
  1714. * then be used to add the message there. Icons are not supported in
  1715. * that case and will be ignored.
  1716. * Pass 'null' to reset/delete the custom handler.
  1717. * Note that there is no notification when a message is supposed to get
  1718. * hidden.
  1719. *
  1720. * @name Alert.setCustomHandler
  1721. * @function
  1722. * @param {function|null} newHandler
  1723. */
  1724. me.setCustomHandler = function (newHandler) {
  1725. customHandler = newHandler;
  1726. };
  1727. /**
  1728. * init status manager
  1729. *
  1730. * preloads HTMLElements
  1731. *
  1732. * @name Alert.init
  1733. * @function
  1734. */
  1735. me.init = function () {
  1736. // hide "no javascript" error message (guard in test environments)
  1737. const noscriptEl = document.getElementById('noscript');
  1738. if (noscriptEl) {
  1739. noscriptEl.style.display = 'none';
  1740. }
  1741. // not a reset, but first set of the elements
  1742. errorMessage = document.getElementById('errormessage');
  1743. loadingIndicator = document.getElementById('loadingindicator');
  1744. statusMessage = document.getElementById('status');
  1745. remainingTime = document.getElementById('remainingtime');
  1746. currentIcon = [
  1747. 'glyphicon-time', // loading icon
  1748. 'glyphicon-info-sign', // status icon
  1749. 'glyphicon-warning-sign', // warning icon
  1750. 'glyphicon-alert' // error icon
  1751. ];
  1752. };
  1753. return me;
  1754. })();
  1755. /**
  1756. * handles paste status/result
  1757. *
  1758. * @name PasteStatus
  1759. * @class
  1760. */
  1761. const PasteStatus = (function () {
  1762. const me = {};
  1763. let pasteSuccess,
  1764. pasteUrl,
  1765. remainingTime,
  1766. shortenButton;
  1767. /**
  1768. * forward to URL shortener
  1769. *
  1770. * @name PasteStatus.sendToShortener
  1771. * @private
  1772. * @function
  1773. */
  1774. function sendToShortener() {
  1775. if (shortenButton.classList.contains('buttondisabled')) {
  1776. return;
  1777. }
  1778. fetch(`${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`, {
  1779. method: 'GET',
  1780. headers: { 'Accept': 'text/html, application/xhtml+xml, application/xml, application/json' },
  1781. credentials: 'omit',
  1782. signal: AbortSignal.timeout(10000)
  1783. })
  1784. .then(response => {
  1785. if (!response.ok) {
  1786. throw new Error('HTTP ' + response.status);
  1787. }
  1788. return response.text();
  1789. })
  1790. .then(data => PasteStatus.extractUrl(data))
  1791. .catch(error => {
  1792. console.error('Shortener error:', error);
  1793. // we don't know why it failed, could be CORS of the external
  1794. // server not setup properly, in which case we follow old
  1795. // behavior to open it in new tab
  1796. window.open(
  1797. `${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`,
  1798. '_blank',
  1799. 'noopener, noreferrer'
  1800. );
  1801. });
  1802. }
  1803. /**
  1804. * Forces opening the document if the link does not do this automatically.
  1805. *
  1806. * This is necessary as browsers will not reload the page when it is
  1807. * already loaded (which is fake as it is set via history.pushState()).
  1808. *
  1809. * @name PasteStatus.pasteLinkClick
  1810. * @function
  1811. */
  1812. function pasteLinkClick() {
  1813. // check if location is (already) shown in URL bar
  1814. if (window.location.href === pasteUrl.href) {
  1815. // if so we need to load link by reloading the current site
  1816. window.location.reload(true);
  1817. }
  1818. }
  1819. /**
  1820. * creates a notification after a successful document upload
  1821. *
  1822. * @name PasteStatus.createPasteNotification
  1823. * @function
  1824. * @param {string} url
  1825. * @param {string} deleteUrl
  1826. */
  1827. me.createPasteNotification = function(url, deleteUrl)
  1828. {
  1829. const ua = navigator.userAgent;
  1830. const isMac = /Mac/.test(ua);
  1831. const hotkey = isMac ? I18n._('Cmd') : I18n._('Ctrl');
  1832. I18n._(
  1833. document.getElementById('pastelink'),
  1834. 'Your document is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit <kbd>%s</kbd>+<kbd>c</kbd> to copy)</span>',
  1835. url, url, hotkey
  1836. );
  1837. // save newly created element
  1838. pasteUrl = document.getElementById('pasteurl');
  1839. // and add click event
  1840. if (pasteUrl) {
  1841. pasteUrl.addEventListener('click', pasteLinkClick);
  1842. }
  1843. // delete link
  1844. const deleteLink = document.getElementById('deletelink');
  1845. if (deleteLink) {
  1846. deleteLink.href = deleteUrl;
  1847. }
  1848. I18n._(document.querySelector('#deletelink span:not(.glyphicon)'), 'Delete data');
  1849. // enable shortener button
  1850. if (shortenButton) {
  1851. shortenButton.classList.remove('buttondisabled');
  1852. }
  1853. // show result
  1854. if (pasteSuccess) {
  1855. pasteSuccess.classList.remove('hidden');
  1856. }
  1857. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1858. Helper.selectText(pasteUrl);
  1859. };
  1860. /**
  1861. * Checks if auto-shortening is enabled and sends the link to the shortener if it is.
  1862. *
  1863. * @name PasteStatus.checkAutoShorten
  1864. * @function
  1865. */
  1866. me.checkAutoShorten = function () {
  1867. // check if auto-shortening is enabled
  1868. if (shortenButton && shortenButton.dataset.autoshorten === 'true') {
  1869. // if so, we send the link to the shortener
  1870. // we do not remove the button, in case shortener fails
  1871. sendToShortener();
  1872. }
  1873. };
  1874. /**
  1875. * extracts URLs from given string
  1876. *
  1877. * if at least one is found, it disables the shortener button and
  1878. * replaces the document URL
  1879. *
  1880. * @name PasteStatus.extractUrl
  1881. * @function
  1882. * @param {string} response
  1883. */
  1884. me.extractUrl = function (response) {
  1885. if (typeof response === 'object') {
  1886. response = JSON.stringify(response);
  1887. }
  1888. if (typeof response === 'string' && response.length > 0) {
  1889. const shortUrlMatcher = /https?:\/\/[^\s"<]+/g; // JSON API will have URL in quotes, XML in tags
  1890. const shortUrl = (response.match(shortUrlMatcher) || []).filter(function (urlRegExMatch) {
  1891. if (typeof URL.canParse === 'function') {
  1892. return URL.canParse(urlRegExMatch);
  1893. }
  1894. // polyfill for older browsers (< 120) & node (< 19.9 & < 18.17)
  1895. try {
  1896. return !!new URL(urlRegExMatch);
  1897. } catch (error) {
  1898. return false;
  1899. }
  1900. }).sort(function (a, b) {
  1901. return a.length - b.length; // shortest first
  1902. })[0];
  1903. if (typeof shortUrl === 'string' && shortUrl.length > 0) {
  1904. // we disable the button to avoid calling shortener again
  1905. if (shortenButton) {
  1906. shortenButton.classList.add('buttondisabled');
  1907. }
  1908. // update link
  1909. pasteUrl.textContent = shortUrl;
  1910. pasteUrl.href = shortUrl;
  1911. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1912. Helper.selectText(pasteUrl);
  1913. CopyToClipboard.setUrl(shortUrl);
  1914. return;
  1915. }
  1916. }
  1917. Alert.showError('Cannot parse response from URL shortener.');
  1918. };
  1919. /**
  1920. * shows the remaining time
  1921. *
  1922. * @name PasteStatus.showRemainingTime
  1923. * @function
  1924. * @param {Paste} paste
  1925. */
  1926. me.showRemainingTime = function (paste) {
  1927. if (paste.isBurnAfterReadingEnabled()) {
  1928. // display document "for your eyes only" if it is deleted
  1929. // the document has been deleted when the JSON with the ciphertext
  1930. // has been downloaded
  1931. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1932. remainingTime.classList.add('foryoureyesonly');
  1933. } else if (paste.getTimeToLive() > 0) {
  1934. // display document expiration
  1935. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1936. expirationLabel = [
  1937. 'This document will expire in %d ' + expiration[1] + '.',
  1938. 'This document will expire in %d ' + expiration[1] + 's.'
  1939. ];
  1940. Alert.showRemaining([expirationLabel, expiration[0]]);
  1941. remainingTime.classList.remove('foryoureyesonly');
  1942. } else {
  1943. // never expires
  1944. return;
  1945. }
  1946. // in the end, display notification
  1947. remainingTime.classList.remove('hidden');
  1948. };
  1949. /**
  1950. * hides the remaining time and successful upload notification
  1951. *
  1952. * @name PasteStatus.hideMessages
  1953. * @function
  1954. */
  1955. me.hideMessages = function () {
  1956. remainingTime.classList.add('hidden');
  1957. pasteSuccess.classList.add('hidden');
  1958. };
  1959. /**
  1960. * init status manager
  1961. *
  1962. * preloads HTMLElements
  1963. *
  1964. * @name PasteStatus.init
  1965. * @function
  1966. */
  1967. me.init = function () {
  1968. pasteSuccess = document.getElementById('pastesuccess');
  1969. // pasteUrl is saved in me.createPasteNotification() after creation
  1970. remainingTime = document.getElementById('remainingtime');
  1971. shortenButton = document.getElementById('shortenbutton');
  1972. // bind elements
  1973. if (shortenButton) {
  1974. shortenButton.addEventListener('click', sendToShortener);
  1975. }
  1976. };
  1977. return me;
  1978. })();
  1979. /**
  1980. * password prompt
  1981. *
  1982. * @name Prompt
  1983. * @class
  1984. */
  1985. const Prompt = (function () {
  1986. const me = {};
  1987. let passwordDecrypt,
  1988. passwordModal,
  1989. bootstrap5PasswordModal = null,
  1990. password = '';
  1991. /**
  1992. * submit a password in the modal dialog
  1993. *
  1994. * @name Prompt.submitPasswordModal
  1995. * @private
  1996. * @function
  1997. * @param {Event} event
  1998. */
  1999. function submitPasswordModal(event) {
  2000. event.preventDefault();
  2001. // get input
  2002. password = passwordDecrypt.value;
  2003. // hide modal
  2004. if (bootstrap5PasswordModal) {
  2005. bootstrap5PasswordModal.hide();
  2006. } else {
  2007. if (passwordModal) {
  2008. passwordModal.classList.remove('show');
  2009. passwordModal.style.display = 'none';
  2010. }
  2011. }
  2012. PasteDecrypter.run();
  2013. }
  2014. /**
  2015. * Request users confirmation to load possibly burn after reading document
  2016. *
  2017. * @name Prompt.requestLoadConfirmation
  2018. * @function
  2019. */
  2020. me.requestLoadConfirmation = function () {
  2021. const loadconfirmmodal = document.getElementById('loadconfirmmodal');
  2022. const loadconfirmOpenNow = loadconfirmmodal.querySelector('#loadconfirm-open-now');
  2023. loadconfirmOpenNow.removeEventListener('click', PasteDecrypter.run);
  2024. loadconfirmOpenNow.addEventListener('click', PasteDecrypter.run);
  2025. const loadconfirmClose = loadconfirmmodal.querySelector('.btn-close');
  2026. loadconfirmClose.removeEventListener('click', Controller.newPaste);
  2027. loadconfirmClose.addEventListener('click', Controller.newPaste);
  2028. loadconfirmmodal.addEventListener('shown.bs.modal', () => {
  2029. loadconfirmOpenNow.focus();
  2030. });
  2031. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2032. (new bootstrap.Modal(loadconfirmmodal)).show();
  2033. } else {
  2034. // minimal fallback: make element visible
  2035. loadconfirmmodal.classList.add('show');
  2036. }
  2037. };
  2038. /**
  2039. * ask the user for the password and set it
  2040. *
  2041. * @name Prompt.requestPassword
  2042. * @function
  2043. */
  2044. me.requestPassword = function () {
  2045. // show new bootstrap method (if available)
  2046. if (passwordModal !== null) {
  2047. if (bootstrap5PasswordModal) {
  2048. bootstrap5PasswordModal.show();
  2049. }
  2050. return;
  2051. }
  2052. PasteDecrypter.run();
  2053. };
  2054. /**
  2055. * get the cached password
  2056. *
  2057. * If you do not get a password with this function
  2058. * (returns an empty string), use requestPassword.
  2059. *
  2060. * @name Prompt.getPassword
  2061. * @function
  2062. * @return {string}
  2063. */
  2064. me.getPassword = function () {
  2065. return password;
  2066. };
  2067. /**
  2068. * resets the password to an empty string
  2069. *
  2070. * @name Prompt.reset
  2071. * @function
  2072. */
  2073. me.reset = function () {
  2074. // reset internal
  2075. password = '';
  2076. // and also reset UI
  2077. passwordDecrypt.value = '';
  2078. };
  2079. /**
  2080. * init status manager
  2081. *
  2082. * preloads HTMLElements
  2083. *
  2084. * @name Prompt.init
  2085. * @function
  2086. */
  2087. me.init = function () {
  2088. passwordDecrypt = document.getElementById('passworddecrypt');
  2089. passwordModal = document.getElementById('passwordmodal');
  2090. // bind events - handle Model password submission
  2091. if (passwordModal) {
  2092. const passwordForm = document.getElementById('passwordform');
  2093. if (passwordForm) {
  2094. passwordForm.addEventListener('submit', submitPasswordModal);
  2095. }
  2096. const disableClosingConfig = {
  2097. backdrop: 'static',
  2098. keyboard: false,
  2099. show: false
  2100. };
  2101. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2102. bootstrap5PasswordModal = new bootstrap.Modal(passwordModal, disableClosingConfig);
  2103. } else {
  2104. // fallback: keep modal hidden until explicitly shown
  2105. passwordModal.style.display = 'none';
  2106. }
  2107. // ensure focus when modal shown (works for bootstrap5)
  2108. passwordModal.addEventListener('shown.bs.modal', () => {
  2109. passwordDecrypt.focus();
  2110. });
  2111. }
  2112. };
  2113. return me;
  2114. })();
  2115. /**
  2116. * Manage paste/message input, and preview tab
  2117. *
  2118. * Note that the actual preview is handled by PasteViewer.
  2119. *
  2120. * @name Editor
  2121. * @class
  2122. */
  2123. const Editor = (function () {
  2124. const me = {};
  2125. let editorTabs,
  2126. messageEdit,
  2127. messageEditParent,
  2128. messagePreview,
  2129. messagePreviewParent,
  2130. messageTab,
  2131. messageTabParent,
  2132. message,
  2133. isPreview = false,
  2134. isTabSupported = true;
  2135. /**
  2136. * support input of tab character
  2137. *
  2138. * @name Editor.supportTabs
  2139. * @function
  2140. * @param {KeyboardEvent} event
  2141. * @this message
  2142. */
  2143. function supportTabs(event) {
  2144. // support disabling tab support using [Esc] and [Ctrl]+[m]
  2145. if (event.key === 'Escape' || (event.ctrlKey && event.key === 'm')) {
  2146. toggleTabSupport();
  2147. if (messageTab) messageTab.checked = isTabSupported;
  2148. event.preventDefault();
  2149. }
  2150. else if (isTabSupported && event.key === 'Tab') {
  2151. // get caret position & selection
  2152. const val = this.value,
  2153. start = this.selectionStart,
  2154. end = this.selectionEnd;
  2155. // set textarea value to: text before caret + tab + text after caret
  2156. this.value = val.substring(0, start) + '\t' + val.substring(end);
  2157. // put caret at right position again
  2158. this.selectionStart = this.selectionEnd = start + 1;
  2159. // prevent the textarea to lose focus
  2160. event.preventDefault();
  2161. }
  2162. }
  2163. /**
  2164. * toggle tab support in message textarea
  2165. *
  2166. * @name Editor.toggleTabSupport
  2167. * @private
  2168. * @function
  2169. */
  2170. function toggleTabSupport() {
  2171. isTabSupported = !isTabSupported;
  2172. }
  2173. /**
  2174. * view the Editor tab
  2175. *
  2176. * @name Editor.viewEditor
  2177. * @function
  2178. * @param {Event} event - optional
  2179. */
  2180. function viewEditor(event) {
  2181. // toggle buttons
  2182. messageEdit.classList.add('active');
  2183. messageEditParent.classList.add('active');
  2184. messagePreview.classList.remove('active');
  2185. messagePreviewParent.classList.remove('active');
  2186. messageEdit.setAttribute('aria-selected', 'true');
  2187. messagePreview.setAttribute('aria-selected', 'false');
  2188. PasteViewer.hide();
  2189. // reshow input
  2190. message.classList.remove('hidden');
  2191. messageTabParent.classList.remove('hidden');
  2192. me.focusInput();
  2193. // finish
  2194. isPreview = false;
  2195. // prevent jumping of page to top
  2196. if (typeof event !== 'undefined') {
  2197. event.preventDefault();
  2198. }
  2199. }
  2200. /**
  2201. * view the preview tab
  2202. *
  2203. * @name Editor.viewPreview
  2204. * @function
  2205. * @param {Event} event
  2206. */
  2207. function viewPreview(event) {
  2208. // toggle buttons
  2209. messageEdit.classList.remove('active');
  2210. messageEditParent.classList.remove('active');
  2211. messagePreview.classList.add('active');
  2212. messagePreviewParent.classList.add('active');
  2213. messageEdit.setAttribute('aria-selected', 'false');
  2214. messagePreview.setAttribute('aria-selected', 'true');
  2215. // hide input as now preview is shown
  2216. message.classList.add('hidden');
  2217. messageTabParent.classList.add('hidden');
  2218. // show preview
  2219. PasteViewer.setText(message.value);
  2220. if (AttachmentViewer.hasAttachmentData()) {
  2221. const attachmentsData = AttachmentViewer.getAttachmentsData();
  2222. attachmentsData.forEach(attachmentData => {
  2223. const mimeType = AttachmentViewer.getAttachmentMimeType(attachmentData);
  2224. AttachmentViewer.handleBlobAttachmentPreview(
  2225. AttachmentViewer.getAttachmentPreview(),
  2226. attachmentData, mimeType
  2227. );
  2228. });
  2229. AttachmentViewer.showAttachment();
  2230. }
  2231. PasteViewer.run();
  2232. // finish
  2233. isPreview = true;
  2234. // prevent jumping of page to top
  2235. if (typeof event !== 'undefined') {
  2236. event.preventDefault();
  2237. }
  2238. }
  2239. /**
  2240. * get the state of the preview
  2241. *
  2242. * @name Editor.isPreview
  2243. * @function
  2244. */
  2245. me.isPreview = function () {
  2246. return isPreview;
  2247. };
  2248. /**
  2249. * reset the Editor view
  2250. *
  2251. * @name Editor.resetInput
  2252. * @function
  2253. */
  2254. me.resetInput = function () {
  2255. // go back to input
  2256. if (isPreview) {
  2257. viewEditor();
  2258. }
  2259. // clear content
  2260. message.value = '';
  2261. };
  2262. /**
  2263. * shows the Editor
  2264. *
  2265. * @name Editor.show
  2266. * @function
  2267. */
  2268. me.show = function () {
  2269. message.classList.remove('hidden');
  2270. messageTabParent.classList.remove('hidden');
  2271. editorTabs.classList.remove('hidden');
  2272. };
  2273. /**
  2274. * hides the Editor
  2275. *
  2276. * @name Editor.hide
  2277. * @function
  2278. */
  2279. me.hide = function () {
  2280. message.classList.add('hidden');
  2281. messageTabParent.classList.add('hidden');
  2282. editorTabs.classList.add('hidden');
  2283. };
  2284. /**
  2285. * focuses the message input
  2286. *
  2287. * @name Editor.focusInput
  2288. * @function
  2289. */
  2290. me.focusInput = function () {
  2291. message.focus();
  2292. };
  2293. /**
  2294. * sets a new text
  2295. *
  2296. * @name Editor.setText
  2297. * @function
  2298. * @param {string} newText
  2299. */
  2300. me.setText = function (newText) {
  2301. message.value = newText;
  2302. };
  2303. /**
  2304. * returns the current text
  2305. *
  2306. * @name Editor.getText
  2307. * @function
  2308. * @return {string}
  2309. */
  2310. me.getText = function () {
  2311. return message.value;
  2312. };
  2313. /**
  2314. * init editor
  2315. *
  2316. * preloads HTMLElements and binds events
  2317. *
  2318. * @name Editor.init
  2319. * @function
  2320. */
  2321. me.init = function () {
  2322. editorTabs = document.getElementById('editorTabs');
  2323. message = document.getElementById('message');
  2324. messageTab = document.getElementById('messagetab');
  2325. messageTabParent = messageTab ? messageTab.parentElement : null;
  2326. // bind events
  2327. if (message) {
  2328. message.addEventListener('keydown', supportTabs);
  2329. }
  2330. if (messageTab) {
  2331. messageTab.addEventListener('change', toggleTabSupport);
  2332. }
  2333. // bind click events to tab switchers (a), and save parents (li)
  2334. messageEdit = document.getElementById('messageedit');
  2335. if (messageEdit) {
  2336. messageEdit.addEventListener('click', viewEditor);
  2337. messageEditParent = messageEdit.parentElement;
  2338. }
  2339. messagePreview = document.getElementById('messagepreview');
  2340. if (messagePreview) {
  2341. messagePreview.addEventListener('click', viewPreview);
  2342. messagePreviewParent = messagePreview.parentElement;
  2343. }
  2344. };
  2345. return me;
  2346. })();
  2347. /**
  2348. * (view) Parse and show document.
  2349. *
  2350. * @name PasteViewer
  2351. * @class
  2352. */
  2353. const PasteViewer = (function () {
  2354. const me = {};
  2355. let messageTabParent,
  2356. placeholder,
  2357. prettyMessage,
  2358. prettyPrintEl,
  2359. plainText,
  2360. text,
  2361. format = 'plaintext',
  2362. isDisplayed = false,
  2363. isChanged = true; // by default true as nothing was parsed yet
  2364. /**
  2365. * apply the set format on paste and displays it
  2366. *
  2367. * @name PasteViewer.parsePaste
  2368. * @private
  2369. * @function
  2370. */
  2371. function parsePaste() {
  2372. // skip parsing if no text is given
  2373. if (text === '') {
  2374. return;
  2375. }
  2376. if (format === 'markdown') {
  2377. const converter = new showdown.Converter({
  2378. disallowRawHTML: true,
  2379. excludeTrailingPunctuationFromURLs: true,
  2380. safeMode: true,
  2381. simplifiedAutoLink: true,
  2382. strikethrough: true,
  2383. tables: true,
  2384. tablesHeaderId: true
  2385. });
  2386. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2387. if (plainText) {
  2388. plainText.innerHTML = DOMPurify.sanitize(
  2389. converter.makeHtml(text),
  2390. purifyHtmlConfig
  2391. );
  2392. // add table classes from bootstrap css
  2393. plainText.querySelectorAll('table').forEach(t => {
  2394. t.classList.add('table-condensed', 'table-bordered');
  2395. });
  2396. }
  2397. } else {
  2398. if (format === 'syntaxhighlighting') {
  2399. // yes, this is really needed to initialize the environment
  2400. if (typeof prettyPrint === 'function') {
  2401. prettyPrint();
  2402. }
  2403. if (prettyPrintEl) {
  2404. prettyPrintEl.innerHTML = prettyPrintOne(
  2405. Helper.htmlEntities(text), null, true
  2406. );
  2407. }
  2408. } else {
  2409. // = 'plaintext'
  2410. if (prettyPrintEl) {
  2411. prettyPrintEl.textContent = text;
  2412. }
  2413. }
  2414. if (prettyPrintEl) {
  2415. Helper.urls2links(prettyPrintEl, format !== 'syntaxhighlighting');
  2416. prettyPrintEl.style.whiteSpace = 'pre-wrap';
  2417. prettyPrintEl.style.wordBreak = 'normal';
  2418. prettyPrintEl.classList.remove('prettyprint', 'prettyprinted');
  2419. }
  2420. }
  2421. }
  2422. /**
  2423. * displays the document
  2424. *
  2425. * NOTE: FOr some obscure reaosn, Markdown is shown in the "plaintext" class
  2426. * and all other ones are rendered in the "prettyPrintEl" one.
  2427. *
  2428. * @name PasteViewer.showPaste
  2429. * @private
  2430. * @function
  2431. */
  2432. function showPaste() {
  2433. // instead of "nothing" better display a placeholder
  2434. if (text === '') {
  2435. if (placeholder) placeholder.classList.remove('hidden');
  2436. return;
  2437. }
  2438. // otherwise hide the placeholder
  2439. if (placeholder) placeholder.classList.add('hidden');
  2440. if (messageTabParent) messageTabParent.classList.add('hidden');
  2441. if (format === 'markdown') {
  2442. if (plainText) plainText.classList.remove('hidden');
  2443. if (prettyMessage) prettyMessage.classList.add('hidden');
  2444. } else {
  2445. if (plainText) plainText.classList.add('hidden');
  2446. if (prettyMessage) prettyMessage.classList.remove('hidden');
  2447. }
  2448. }
  2449. /**
  2450. * sets the format in which the text is shown
  2451. *
  2452. * @name PasteViewer.setFormat
  2453. * @function
  2454. * @param {string} newFormat the new format
  2455. */
  2456. me.setFormat = function (newFormat) {
  2457. // skip if there is no update
  2458. if (format === newFormat) {
  2459. return;
  2460. }
  2461. // needs to update display too, if we switch from or to Markdown
  2462. if (format === 'markdown' || newFormat === 'markdown') {
  2463. isDisplayed = false;
  2464. }
  2465. format = newFormat;
  2466. isChanged = true;
  2467. // update preview
  2468. if (Editor.isPreview()) {
  2469. PasteViewer.run();
  2470. }
  2471. };
  2472. /**
  2473. * returns the current format
  2474. *
  2475. * @name PasteViewer.getFormat
  2476. * @function
  2477. * @return {string}
  2478. */
  2479. me.getFormat = function () {
  2480. return format;
  2481. };
  2482. /**
  2483. * returns whether the current view is pretty printed
  2484. *
  2485. * @name PasteViewer.isPrettyPrinted
  2486. * @function
  2487. * @return {bool}
  2488. */
  2489. me.isPrettyPrinted = function () {
  2490. return prettyPrintEl ? prettyPrintEl.classList.contains('prettyprinted') : false;
  2491. };
  2492. /**
  2493. * sets the text to show
  2494. *
  2495. * @name PasteViewer.setText
  2496. * @function
  2497. * @param {string} newText the text to show
  2498. */
  2499. me.setText = function (newText) {
  2500. if (text !== newText) {
  2501. text = newText;
  2502. isChanged = true;
  2503. }
  2504. };
  2505. /**
  2506. * gets the current cached text
  2507. *
  2508. * @name PasteViewer.getText
  2509. * @function
  2510. * @return {string}
  2511. */
  2512. me.getText = function () {
  2513. return text;
  2514. };
  2515. /**
  2516. * show/update the parsed text (preview)
  2517. *
  2518. * @name PasteViewer.run
  2519. * @function
  2520. */
  2521. me.run = function () {
  2522. if (isChanged) {
  2523. parsePaste();
  2524. isChanged = false;
  2525. }
  2526. if (!isDisplayed) {
  2527. showPaste();
  2528. isDisplayed = true;
  2529. }
  2530. };
  2531. /**
  2532. * hide parsed text (preview)
  2533. *
  2534. * @name PasteViewer.hide
  2535. * @function
  2536. */
  2537. me.hide = function () {
  2538. if (!isDisplayed) {
  2539. return;
  2540. }
  2541. if (plainText) plainText.classList.add('hidden');
  2542. if (prettyMessage) prettyMessage.classList.add('hidden');
  2543. if (placeholder) placeholder.classList.add('hidden');
  2544. AttachmentViewer.hideAttachmentPreview();
  2545. isDisplayed = false;
  2546. };
  2547. /**
  2548. * init status manager
  2549. *
  2550. * preloads DOM elements
  2551. *
  2552. * @name PasteViewer.init
  2553. * @function
  2554. */
  2555. me.init = function () {
  2556. const messagetab = document.getElementById('messagetab');
  2557. messageTabParent = messagetab ? messagetab.parentElement : null;
  2558. placeholder = document.getElementById('placeholder');
  2559. plainText = document.getElementById('plaintext');
  2560. prettyMessage = document.getElementById('prettymessage');
  2561. prettyPrintEl = document.getElementById('prettyprint');
  2562. // get default option from template/HTML or fall back to set value
  2563. format = Model.getFormatDefault() || format;
  2564. text = '';
  2565. isDisplayed = false;
  2566. isChanged = true;
  2567. };
  2568. return me;
  2569. })();
  2570. /**
  2571. * (view) Show attachment and preview if possible
  2572. *
  2573. * @name AttachmentViewer
  2574. * @class
  2575. */
  2576. const AttachmentViewer = (function () {
  2577. const me = {};
  2578. let attachmentPreview,
  2579. attachment,
  2580. attachmentsData = [],
  2581. files,
  2582. fileInput,
  2583. dragAndDropFileNames,
  2584. dropzone;
  2585. /**
  2586. * get blob URL from string data and mime type
  2587. *
  2588. * @name AttachmentViewer.getBlobUrl
  2589. * @private
  2590. * @function
  2591. * @param {string} data - raw data of attachment
  2592. * @param {string} data - mime type of attachment
  2593. * @return {string} objectURL
  2594. */
  2595. function getBlobUrl(data, mimeType) {
  2596. // Transform into a Blob
  2597. const buf = Uint8Array.from(
  2598. data,
  2599. character => character.charCodeAt(0)
  2600. );
  2601. const blob = new window.Blob(
  2602. [buf],
  2603. {
  2604. type: mimeType
  2605. }
  2606. );
  2607. // Get blob URL
  2608. return window.URL.createObjectURL(blob);
  2609. }
  2610. /**
  2611. * sets the attachment but does not yet show it
  2612. *
  2613. * @name AttachmentViewer.setAttachment
  2614. * @function
  2615. * @param {string} attachmentData - base64-encoded data of file
  2616. * @param {string} fileName - optional, file name
  2617. */
  2618. me.setAttachment = function (attachmentData, fileName) {
  2619. // skip, if attachments got disabled
  2620. if (!attachment) return;
  2621. // data URI format: data:[<mimeType>][;base64],<data>
  2622. const template = Model.getTemplate('attachment');
  2623. const attachmentLink = template.querySelector('a');
  2624. // position in data URI string of where data begins
  2625. const base64Start = attachmentData.indexOf(',') + 1;
  2626. const mimeType = me.getAttachmentMimeType(attachmentData);
  2627. // We explicitly do _not_ use the original mime type for the download link
  2628. // to always force a download instead of potentially dangerous browser rendering/parsing/interpretation
  2629. let sanitizedMimeType = 'application/octet-stream';
  2630. if (me.isSafeMimeType(mimeType)) {
  2631. sanitizedMimeType = mimeType;
  2632. }
  2633. // extract data and convert to binary
  2634. const base64Data = attachmentData.substring(base64Start);
  2635. const plainData = base64Data.length > 0 ? atob(base64Data) : '';
  2636. let blobUrl = getBlobUrl(plainData, sanitizedMimeType);
  2637. attachmentLink.setAttribute('href', blobUrl);
  2638. if (typeof fileName !== 'undefined') {
  2639. attachmentLink.setAttribute('download', fileName);
  2640. const fileSize = Helper.formatBytes(plainData.length);
  2641. const spans = template.querySelectorAll('span');
  2642. const span = spans[spans.length - 1];
  2643. span.textContent += ` (${fileName}, ${fileSize})`;
  2644. }
  2645. // sanitize SVG preview
  2646. // prevents executing embedded scripts when CSP is not set and user
  2647. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2648. // in the preview by use of an img tag, which disables scripts, too
  2649. if (mimeType.startsWith('image/svg')) {
  2650. try {
  2651. // attempt to UTF-8 decode the SVG data
  2652. const svgBuffer = Uint8Array.from(
  2653. plainData,
  2654. character => character.charCodeAt(0)
  2655. );
  2656. const utf8ValidatedSvgString = new TextDecoder(
  2657. 'utf-8',
  2658. {fatal: true}
  2659. ).decode(svgBuffer);
  2660. const sanitizedData = DOMPurify.sanitize(
  2661. utf8ValidatedSvgString,
  2662. purifySvgConfig
  2663. );
  2664. sanitizedMimeType = 'image/svg+xml';
  2665. blobUrl = getBlobUrl(sanitizedData, sanitizedMimeType);
  2666. } catch (e) {
  2667. // Invalid or non-UTF-8 SVG: download only, no preview as it
  2668. // may be used to smuggle multi-byte sequences past DOMpurify
  2669. // such as `&#x13c` to get `\x01<` & `&#x13e` to get `\x01>`
  2670. sanitizedMimeType = 'application/octet-stream';
  2671. blobUrl = getBlobUrl(plainData, sanitizedMimeType);
  2672. }
  2673. }
  2674. template.classList.remove('hidden');
  2675. attachment.appendChild(template);
  2676. me.handleBlobAttachmentPreview(attachmentPreview, blobUrl, sanitizedMimeType);
  2677. };
  2678. /**
  2679. * Evaluates whether this is known a safe mime type.
  2680. *
  2681. * This means, the media can safely be displayed and e.g. no XSS should be possible.
  2682. *
  2683. * @name AttachmentViewer.isSafeMimeType
  2684. * @function
  2685. * @param {string}
  2686. * @returns {bool}
  2687. */
  2688. me.isSafeMimeType = function(mimeType) {
  2689. return ((
  2690. mimeType.startsWith('image/') &&
  2691. !/svg/i.test(mimeType)
  2692. ) ||
  2693. mimeType.startsWith('video/') ||
  2694. mimeType.startsWith('audio/') ||
  2695. mimeType === 'application/pdf' ||
  2696. mimeType === 'text/plain') &&
  2697. // don't accept comments, stray characters, spaces, etc.
  2698. /^[a-z0-9][a-z0-9.-]*[a-z0-9]\/[a-z0-9][a-z0-9.+-]*[a-z0-9]$/.test(mimeType);
  2699. };
  2700. /**
  2701. * displays the attachment and (if possible) the preview
  2702. *
  2703. * @name AttachmentViewer.showAttachment
  2704. * @function
  2705. */
  2706. me.showAttachment = function () {
  2707. if (!attachment) {
  2708. return;
  2709. }
  2710. attachment.classList.remove('hidden');
  2711. if (attachmentPreview && me.hasAttachmentPreview()) {
  2712. attachmentPreview.classList.remove('hidden');
  2713. }
  2714. };
  2715. /**
  2716. * removes the attachment
  2717. *
  2718. * This automatically hides the attachment containers too, to
  2719. * prevent an inconsistent display.
  2720. *
  2721. * @name AttachmentViewer.removeAttachment
  2722. * @function
  2723. */
  2724. me.removeAttachment = function () {
  2725. if (!attachment) {
  2726. return;
  2727. }
  2728. me.hideAttachment();
  2729. me.hideAttachmentPreview();
  2730. attachment.innerHTML = '';
  2731. if (attachmentPreview) {
  2732. attachmentPreview.innerHTML = '';
  2733. }
  2734. me.clearDragAndDrop();
  2735. AttachmentViewer.removeAttachmentData();
  2736. };
  2737. /**
  2738. * removes the attachment data
  2739. *
  2740. * This removes the data, which would be uploaded otherwise.
  2741. *
  2742. * @name AttachmentViewer.removeAttachmentData
  2743. * @function
  2744. */
  2745. me.removeAttachmentData = function () {
  2746. files = [];
  2747. attachmentsData = [];
  2748. };
  2749. /**
  2750. * Cleares the drag & drop data.
  2751. *
  2752. * @name AttachmentViewer.clearDragAndDrop
  2753. * @function
  2754. */
  2755. me.clearDragAndDrop = function () {
  2756. if (dragAndDropFileNames) {
  2757. dragAndDropFileNames.innerHTML = '';
  2758. }
  2759. };
  2760. /**
  2761. * Print file names added via drag & drop
  2762. *
  2763. * @name AttachmentViewer.printDragAndDropFileNames
  2764. * @private
  2765. * @function
  2766. * @param {string[]} fileNames
  2767. */
  2768. function printDragAndDropFileNames(fileNames) {
  2769. me.clearDragAndDrop();
  2770. fileNames.forEach(fileName => {
  2771. const name = document.createTextNode(fileName);
  2772. dragAndDropFileNames.appendChild(name);
  2773. dragAndDropFileNames.appendChild(document.createElement('br'));
  2774. });
  2775. }
  2776. /**
  2777. * hides the attachment
  2778. *
  2779. * This will not hide the preview (see {@see AttachmentViewer.hideAttachmentPreview}
  2780. * for that) nor will it hide the attachment link if it was moved somewhere
  2781. * else (see {@see AttachmentViewer.moveAttachmentTo}).
  2782. *
  2783. * @name AttachmentViewer.hideAttachment
  2784. * @function
  2785. */
  2786. me.hideAttachment = function () {
  2787. attachment.classList.add('hidden');
  2788. };
  2789. /**
  2790. * hides the attachment preview
  2791. *
  2792. * @name AttachmentViewer.hideAttachmentPreview
  2793. * @function
  2794. */
  2795. me.hideAttachmentPreview = function () {
  2796. if (attachmentPreview) {
  2797. attachmentPreview.classList.add('hidden');
  2798. }
  2799. };
  2800. /**
  2801. * checks if has any attachment preview that is currently rendered
  2802. *
  2803. * Note: This does not verify if the attachment preview is actually shown to the user, as it might be hidden ({@see AttachmentViewer.hideAttachmentPreview}).
  2804. *
  2805. * @name AttachmentViewer.hasAttachmentPreview
  2806. * @function
  2807. * @return {boolean}
  2808. */
  2809. me.hasAttachmentPreview = function () {
  2810. return attachmentPreview.children.length > 0;
  2811. };
  2812. /**
  2813. * checks if there is an attachment displayed
  2814. *
  2815. * @name AttachmentViewer.hasAttachment
  2816. * @function
  2817. */
  2818. me.hasAttachment = function () {
  2819. if (!attachment) {
  2820. return false;
  2821. }
  2822. // Check if there are actual attachment data items (not just UI elements)
  2823. if (attachmentsData.length > 0) {
  2824. return true;
  2825. }
  2826. // Also check UI elements in case data was removed but UI wasn't updated
  2827. return attachment.children.length > 0;
  2828. };
  2829. /**
  2830. * checks if there is attachment data (for preview!) available
  2831. *
  2832. * It returns true, when there is data that needs to be encrypted.
  2833. *
  2834. * @name AttachmentViewer.hasAttachmentData
  2835. * @function
  2836. */
  2837. me.hasAttachmentData = function()
  2838. {
  2839. // Check if there are actual attachment data items (not just UI elements)
  2840. return attachmentsData.length > 0;
  2841. };
  2842. /**
  2843. * return the attachments
  2844. *
  2845. * @name AttachmentViewer.getAttachments
  2846. * @function
  2847. * @returns {array}
  2848. */
  2849. me.getAttachments = function () {
  2850. return [...attachment.querySelectorAll('a')].map(link => (
  2851. [
  2852. link.href,
  2853. link.download
  2854. ]
  2855. ));
  2856. };
  2857. /**
  2858. * Get attachment mime type
  2859. *
  2860. * @name AttachmentViewer.getAttachmentMimeType
  2861. * @function
  2862. * @param {string} attachmentData - Base64 string
  2863. */
  2864. me.getAttachmentMimeType = function (attachmentData) {
  2865. // position in data URI string of where mimeType ends
  2866. const mimeTypeEnd = attachmentData.indexOf(';');
  2867. if (mimeTypeEnd < 6) {
  2868. return '';
  2869. }
  2870. // extract mimeType
  2871. return attachmentData.substring(5, mimeTypeEnd).toLowerCase();
  2872. };
  2873. /**
  2874. * moves the attachment link to another element
  2875. *
  2876. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2877. *
  2878. * @name AttachmentViewer.moveAttachmentTo
  2879. * @function
  2880. * @param {HTMLElement} element - the wrapper/container element where this should be moved to
  2881. * @param {array} attachment - attachment data
  2882. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2883. */
  2884. me.moveAttachmentTo = function (element, attachment, label) {
  2885. const attachmentLink = document.createElement('a');
  2886. attachmentLink.className = 'alert-link';
  2887. attachmentLink.href = attachment[0];
  2888. attachmentLink.download = attachment[1];
  2889. // move element to new place
  2890. element.appendChild(attachmentLink);
  2891. // update text - ensuring no HTML is inserted into the text node
  2892. I18n._(attachmentLink, label, attachment[1]);
  2893. };
  2894. /**
  2895. * read files data as data URL using the FileReader API
  2896. *
  2897. * @name AttachmentViewer.readFileData
  2898. * @private
  2899. * @function
  2900. * @param {FileList[]} loadedFiles (optional) loaded files array
  2901. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2902. */
  2903. function readFileData(loadedFiles = []) {
  2904. // Clear old cache
  2905. me.removeAttachmentData();
  2906. if (typeof FileReader === 'undefined') {
  2907. // revert loading status…
  2908. me.hideAttachment();
  2909. me.hideAttachmentPreview();
  2910. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2911. return;
  2912. }
  2913. if (loadedFiles && loadedFiles.length > 0) {
  2914. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2915. printDragAndDropFileNames(fileNames);
  2916. } else {
  2917. const fileInput = document.getElementById('file');
  2918. if (fileInput && fileInput.files) {
  2919. loadedFiles = [...fileInput.files];
  2920. }
  2921. me.clearDragAndDrop();
  2922. }
  2923. if (loadedFiles.length > 0) {
  2924. files = loadedFiles;
  2925. loadedFiles.forEach((loadedFile, index) => {
  2926. const fileReader = new FileReader();
  2927. fileReader.onload = function (event) {
  2928. const dataURL = event.target.result;
  2929. if (dataURL) {
  2930. attachmentsData[index] = dataURL;
  2931. }
  2932. if (Editor.isPreview()) {
  2933. me.handleAttachmentPreview(attachmentPreview, dataURL);
  2934. attachmentPreview.classList.remove('hidden');
  2935. }
  2936. TopNav.highlightFileupload();
  2937. };
  2938. fileReader.readAsDataURL(loadedFile);
  2939. });
  2940. } else {
  2941. me.removeAttachmentData();
  2942. }
  2943. }
  2944. /**
  2945. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2946. *
  2947. * @name AttachmentViewer.handleBlobAttachmentPreview
  2948. * @function
  2949. * @argument {HTMLElement?} targetElement element where the preview should be appended
  2950. * @argument {string} blobUrl as a blob URL
  2951. * @argument {string} mimeType type
  2952. */
  2953. me.handleBlobAttachmentPreview = function (targetElement, blobUrl, mimeType) {
  2954. if (!targetElement) {
  2955. console.log('Attachment preview element not found/disabled, cannot show attachment preview.');
  2956. return;
  2957. }
  2958. const alreadyIncludesCurrentAttachment = targetElement.querySelectorAll(`[src='${blobUrl}']`).length > 0;
  2959. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  2960. if (mimeType.startsWith('image/')) {
  2961. const image = document.createElement('img');
  2962. image.setAttribute('src', blobUrl);
  2963. image.setAttribute('class', 'img-thumbnail');
  2964. targetElement.appendChild(image);
  2965. } else if (mimeType.startsWith('video/')) {
  2966. const video = document.createElement('video');
  2967. video.setAttribute('controls', 'true');
  2968. video.setAttribute('autoplay', 'true');
  2969. video.setAttribute('class', 'img-thumbnail');
  2970. const source = document.createElement('source');
  2971. source.setAttribute('type', mimeType);
  2972. source.setAttribute('src', blobUrl);
  2973. video.appendChild(source);
  2974. targetElement.appendChild(video);
  2975. } else if (mimeType.startsWith('audio/')) {
  2976. const audio = document.createElement('audio');
  2977. audio.setAttribute('controls', 'true');
  2978. audio.setAttribute('autoplay', 'true');
  2979. const source = document.createElement('source');
  2980. source.setAttribute('type', mimeType);
  2981. source.setAttribute('src', blobUrl);
  2982. audio.appendChild(source);
  2983. targetElement.appendChild(audio);
  2984. } else if (mimeType === 'application/pdf') {
  2985. const embed = document.createElement('embed');
  2986. embed.setAttribute('src', blobUrl);
  2987. embed.setAttribute('type', 'application/pdf');
  2988. embed.setAttribute('class', 'pdfPreview');
  2989. // Fallback for browsers, that don't support the vh unit
  2990. embed.style.height = window.innerHeight + 'px';
  2991. targetElement.appendChild(embed);
  2992. }
  2993. }
  2994. };
  2995. /**
  2996. * attaches the file attachment drag & drop handler to the page
  2997. *
  2998. * @name AttachmentViewer.addDragDropHandler
  2999. * @private
  3000. * @function
  3001. */
  3002. function addDragDropHandler() {
  3003. if (typeof fileInput === 'undefined' || fileInput === null) {
  3004. return;
  3005. }
  3006. const handleDragEnterOrOver = function (event) {
  3007. event.stopPropagation();
  3008. event.preventDefault();
  3009. return false;
  3010. };
  3011. const handleDrop = function (event) {
  3012. event.stopPropagation();
  3013. event.preventDefault();
  3014. if (TopNav.isAttachmentReadonly()) {
  3015. return false;
  3016. }
  3017. if (fileInput) {
  3018. const files = [...event.dataTransfer.files];
  3019. //Clear the file input:
  3020. fileInput.value = '';
  3021. //Only works in Chrome:
  3022. //fileInput.files = event.dataTransfer.files;
  3023. readFileData(files);
  3024. }
  3025. };
  3026. draghover(document);
  3027. document.addEventListener('draghoverstart', function (e) {
  3028. if (TopNav.isAttachmentReadonly()) {
  3029. e.stopPropagation();
  3030. e.preventDefault();
  3031. return false;
  3032. }
  3033. // show dropzone to indicate drop support
  3034. dropzone.classList.remove('hidden');
  3035. });
  3036. document.addEventListener('draghoverend', function () {
  3037. dropzone.classList.add('hidden');
  3038. });
  3039. document.addEventListener('drop', handleDrop);
  3040. document.addEventListener('dragenter', handleDragEnterOrOver);
  3041. document.addEventListener('dragover', handleDragEnterOrOver);
  3042. fileInput.addEventListener('change', function () {
  3043. readFileData();
  3044. });
  3045. }
  3046. /**
  3047. * attaches the clipboard attachment handler to the page
  3048. *
  3049. * @name AttachmentViewer.addClipboardEventHandler
  3050. * @private
  3051. * @function
  3052. */
  3053. function addClipboardEventHandler() {
  3054. document.addEventListener('paste', (event) => {
  3055. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3056. const files = [...items]
  3057. .filter(item => item.kind === 'file')
  3058. .map(item => item.getAsFile());
  3059. if (TopNav.isAttachmentReadonly() && files.length) {
  3060. event.stopPropagation();
  3061. event.preventDefault();
  3062. return false;
  3063. }
  3064. if (files.length) {
  3065. readFileData(files);
  3066. }
  3067. });
  3068. }
  3069. /**
  3070. * getter for attachment data
  3071. *
  3072. * @name AttachmentViewer.getAttachmentsData
  3073. * @function
  3074. * @return {string[]}
  3075. */
  3076. me.getAttachmentsData = function () {
  3077. return attachmentsData;
  3078. };
  3079. /**
  3080. * getter for attachment preview
  3081. *
  3082. * @name AttachmentViewer.getAttachmentPreview
  3083. * @function
  3084. * @return {HTMLElement}
  3085. */
  3086. me.getAttachmentPreview = function () {
  3087. return attachmentPreview;
  3088. };
  3089. /**
  3090. * getter for files data, returns the file list
  3091. *
  3092. * @name AttachmentViewer.getFiles
  3093. * @function
  3094. * @return {FileList[]}
  3095. */
  3096. me.getFiles = function () {
  3097. return files;
  3098. };
  3099. /**
  3100. * initiate
  3101. *
  3102. * preloads HTMLElements
  3103. *
  3104. * @name AttachmentViewer.init
  3105. * @function
  3106. */
  3107. me.init = function () {
  3108. attachment = document.getElementById('attachment');
  3109. dragAndDropFileNames = document.getElementById('dragAndDropFileName');
  3110. dropzone = document.getElementById('dropzone');
  3111. if (attachment) {
  3112. attachmentPreview = document.getElementById('attachmentPreview');
  3113. fileInput = document.getElementById('file');
  3114. addDragDropHandler();
  3115. addClipboardEventHandler();
  3116. }
  3117. };
  3118. return me;
  3119. })();
  3120. /**
  3121. * (view) Shows discussion thread and handles replies
  3122. *
  3123. * @name DiscussionViewer
  3124. * @class
  3125. */
  3126. const DiscussionViewer = (function () {
  3127. const me = {};
  3128. let commentTail,
  3129. discussion,
  3130. reply,
  3131. replyMessage,
  3132. replyNickname,
  3133. replyStatus,
  3134. commentContainer,
  3135. replyCommentId;
  3136. /**
  3137. * initializes the templates
  3138. *
  3139. * @name DiscussionViewer.initTemplates
  3140. * @private
  3141. * @function
  3142. */
  3143. function initTemplates() {
  3144. reply = Model.getTemplate('reply');
  3145. replyMessage = reply.querySelector('#replymessage');
  3146. replyNickname = reply.querySelector('#nickname');
  3147. replyStatus = reply.querySelector('#replystatus');
  3148. // cache elements
  3149. commentTail = Model.getTemplate('commenttail');
  3150. const replyButton = reply.querySelector('#replybutton');
  3151. if (replyButton) {
  3152. replyButton.addEventListener('click', PasteEncrypter.sendComment);
  3153. }
  3154. addEventListeners();
  3155. }
  3156. /**
  3157. * open the comment entry when clicking the "Reply" button of a comment
  3158. *
  3159. * @name DiscussionViewer.openReply
  3160. * @private
  3161. * @function
  3162. * @param {Event} event
  3163. */
  3164. function openReply(event) {
  3165. const source = event.currentTarget || event.target;
  3166. // show all reply buttons
  3167. commentContainer.querySelectorAll('button').forEach(btn => btn.classList.remove('hidden'));
  3168. // hide the current reply button
  3169. source.classList.add('hidden');
  3170. // clear input
  3171. replyMessage.value = '';
  3172. replyNickname.value = '';
  3173. // get comment id from source element
  3174. replyCommentId = source.parentElement.id.split('_')[1];
  3175. // move to correct position
  3176. const parent = source.parentNode;
  3177. if (parent && !reply.contains(source)) {
  3178. if (typeof source.after === 'function') {
  3179. source.after(reply);
  3180. } else if (source.nextSibling) {
  3181. parent.insertBefore(reply, source.nextSibling);
  3182. } else {
  3183. parent.appendChild(reply);
  3184. }
  3185. }
  3186. // show
  3187. reply.classList.remove('hidden');
  3188. replyMessage.focus();
  3189. event.preventDefault();
  3190. }
  3191. /**
  3192. * custom handler for displaying notifications in own status message area
  3193. *
  3194. * @name DiscussionViewer.handleNotification
  3195. * @function
  3196. * @param {string} alertType
  3197. * @return {Boolean|HTMLElement}
  3198. */
  3199. me.handleNotification = function (alertType) {
  3200. // ignore loading messages
  3201. if (alertType === 'loading') {
  3202. return false;
  3203. }
  3204. if (alertType === 'danger') {
  3205. replyStatus.classList.remove('alert-info');
  3206. replyStatus.classList.add('alert-danger');
  3207. const replyIcon = replyStatus.querySelector(':first-child');
  3208. if (replyIcon) {
  3209. replyIcon.classList.remove('glyphicon-alert');
  3210. replyIcon.classList.add('glyphicon-info-sign');
  3211. }
  3212. } else {
  3213. replyStatus.classList.remove('alert-danger');
  3214. replyStatus.classList.add('alert-info');
  3215. const replyIcon = replyStatus.querySelector(':first-child');
  3216. if (replyIcon) {
  3217. replyIcon.classList.remove('glyphicon-info-sign');
  3218. replyIcon.classList.add('glyphicon-alert');
  3219. }
  3220. }
  3221. return replyStatus;
  3222. };
  3223. /**
  3224. * adds another comment
  3225. *
  3226. * @name DiscussionViewer.addComment
  3227. * @function
  3228. * @param {Comment} comment
  3229. * @param {string} commentText
  3230. * @param {string} nickname
  3231. */
  3232. me.addComment = function (comment, commentText, nickname) {
  3233. if (commentText === '') {
  3234. commentText = 'comment decryption failed';
  3235. }
  3236. // create new comment based on template
  3237. const commentEntry = Model.getTemplate('comment');
  3238. if (!commentEntry) {
  3239. return;
  3240. }
  3241. commentEntry.id = 'comment_' + comment.id;
  3242. const commentEntryData = commentEntry.querySelector('div.commentdata');
  3243. if (!commentEntryData) {
  3244. return;
  3245. }
  3246. // set & parse text
  3247. commentEntryData.textContent = commentText;
  3248. Helper.urls2links(commentEntryData);
  3249. // set nickname
  3250. if (nickname.length > 0) {
  3251. const nicknameElement = commentEntry.querySelector('span.nickname');
  3252. if (nicknameElement) {
  3253. nicknameElement.textContent = nickname;
  3254. }
  3255. } else {
  3256. const anonCommenter = document.createElement('em');
  3257. anonCommenter.textContent = I18n._('Anonymous');
  3258. const nicknameElement = commentEntry.querySelector('span.nickname');
  3259. if (nicknameElement) {
  3260. nicknameElement.innerHTML = '';
  3261. nicknameElement.appendChild(anonCommenter);
  3262. }
  3263. }
  3264. // set date
  3265. const created = comment.getCreated();
  3266. const commentDate = created === 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3267. const dateSpan = commentEntry.querySelector('span.commentdate');
  3268. if (dateSpan) {
  3269. dateSpan.textContent = commentDate;
  3270. dateSpan.setAttribute('title', 'CommentID: ' + comment.id);
  3271. }
  3272. // if an avatar is available, display it
  3273. const icon = comment.getIcon();
  3274. if (icon) {
  3275. const iconTitle = 'Avatar generated from IP address';
  3276. const image = document.createElement('img');
  3277. // Set the title immediately with the current translation. If
  3278. // the language has not been loaded yet, this will fall back to
  3279. // English, so we also register a callback to re-apply the
  3280. // translation once available. To avoid a race condition, we
  3281. // register the callback first, then translate - if the language
  3282. // loads between the two lines, both will set the translated text.
  3283. I18n.onLanguageLoaded(function () {
  3284. image.setAttribute('title', I18n._(iconTitle));
  3285. });
  3286. image.setAttribute('title', I18n._(iconTitle));
  3287. image.setAttribute('src', icon);
  3288. image.setAttribute('class', 'vizhash');
  3289. const nickSpan = commentEntry.querySelector('span.nickname');
  3290. if (nickSpan) {
  3291. nickSpan.prepend(' ');
  3292. nickSpan.prepend(image);
  3293. }
  3294. }
  3295. // starting point (default value/fallback)
  3296. let place = commentContainer;
  3297. // if parent comment exists
  3298. const parentComment = document.getElementById('comment_' + comment.parentid);
  3299. if (parentComment) {
  3300. // use parent as position for new comment, so it is shifted
  3301. // to the right
  3302. place = parentComment;
  3303. }
  3304. // attach button handler before inserting
  3305. const replyButton = commentEntry.querySelector('button');
  3306. if (replyButton) {
  3307. replyButton.addEventListener('click', openReply);
  3308. }
  3309. // finally append comment
  3310. place.appendChild(commentEntry);
  3311. };
  3312. /**
  3313. * finishes the discussion area after last comment
  3314. *
  3315. * @name DiscussionViewer.finishDiscussion
  3316. * @function
  3317. */
  3318. me.finishDiscussion = function () {
  3319. // add 'add new comment' area
  3320. const tail = commentTail.cloneNode(true);
  3321. const tailButton = tail.querySelector('button');
  3322. if (tailButton) {
  3323. tailButton.addEventListener('click', openReply);
  3324. }
  3325. commentContainer.appendChild(tail);
  3326. // show discussions
  3327. discussion.classList.remove('hidden');
  3328. };
  3329. /**
  3330. * removes the old discussion and prepares everything for creating a new
  3331. * one.
  3332. *
  3333. * @name DiscussionViewer.prepareNewDiscussion
  3334. * @function
  3335. */
  3336. me.prepareNewDiscussion = function () {
  3337. commentContainer.innerHTML = '';
  3338. discussion.classList.add('hidden');
  3339. // (re-)init templates
  3340. initTemplates();
  3341. };
  3342. /**
  3343. * returns the users message from the reply form
  3344. *
  3345. * @name DiscussionViewer.getReplyMessage
  3346. * @function
  3347. * @return {String}
  3348. */
  3349. me.getReplyMessage = function () {
  3350. return replyMessage.value;
  3351. };
  3352. /**
  3353. * returns the users nickname (if any) from the reply form
  3354. *
  3355. * @name DiscussionViewer.getReplyNickname
  3356. * @function
  3357. * @return {String}
  3358. */
  3359. me.getReplyNickname = function () {
  3360. return replyNickname.value;
  3361. };
  3362. /**
  3363. * returns the id of the parent comment the user is replying to
  3364. *
  3365. * @name DiscussionViewer.getReplyCommentId
  3366. * @function
  3367. * @return {number|undefined}
  3368. */
  3369. me.getReplyCommentId = function () {
  3370. return replyCommentId;
  3371. };
  3372. /**
  3373. * highlights a specific comment and scrolls to it if necessary
  3374. *
  3375. * @name DiscussionViewer.highlightComment
  3376. * @function
  3377. * @param {string} commentId
  3378. * @param {Boolean} fadeOut - whether to fade out the comment
  3379. */
  3380. me.highlightComment = function (commentId, fadeOut) {
  3381. const comment = document.getElementById('comment_' + commentId);
  3382. // in case comment does not exist, cancel
  3383. if (!comment) {
  3384. return;
  3385. }
  3386. comment.classList.add('highlight');
  3387. if (fadeOut === true) {
  3388. setTimeout(function () {
  3389. comment.classList.remove('highlight');
  3390. }, 300);
  3391. }
  3392. if (('checkVisibility' in comment ? comment.checkVisibility() : comment.offsetParent !== null) === false) {
  3393. if (typeof comment.scrollIntoView === 'function') {
  3394. comment.scrollIntoView({ block: 'center' });
  3395. }
  3396. }
  3397. };
  3398. /**
  3399. * Binds events to templates (**and** all )
  3400. */
  3401. function addEventListeners() {
  3402. //
  3403. document.querySelectorAll('#commenttail button')
  3404. .forEach(btn => btn.addEventListener('click', openReply));
  3405. document.querySelectorAll('#comment button')
  3406. .forEach(btn => btn.addEventListener('click', openReply));
  3407. }
  3408. /**
  3409. * initiate
  3410. *
  3411. * preloads HTML elements
  3412. *
  3413. * @name DiscussionViewer.init
  3414. * @function
  3415. */
  3416. me.init = function () {
  3417. // todo: remove
  3418. addEventListeners();
  3419. commentContainer = document.getElementById('commentcontainer');
  3420. discussion = document.getElementById('discussion');
  3421. };
  3422. return me;
  3423. })();
  3424. /**
  3425. * Manage top (navigation) bar
  3426. *
  3427. * @name TopNav
  3428. * @param {object} window
  3429. * @param {object} document
  3430. * @class
  3431. */
  3432. const TopNav = (function (window, document) {
  3433. const me = {};
  3434. let createButtonsDisplayed = false,
  3435. viewButtonsDisplayed = false,
  3436. burnAfterReadingDefault = false,
  3437. openDiscussionDefault = false,
  3438. attach,
  3439. burnAfterReading,
  3440. burnAfterReadingOption,
  3441. cloneButton,
  3442. customAttachment,
  3443. expiration,
  3444. fileRemoveButton,
  3445. fileWrap,
  3446. formatter,
  3447. newButton,
  3448. openDiscussion,
  3449. openDiscussionOption,
  3450. password,
  3451. passwordInput,
  3452. rawTextButton,
  3453. downloadTextButton,
  3454. qrCodeLink,
  3455. emailLink,
  3456. sendButton,
  3457. retryButton,
  3458. pasteExpiration = null,
  3459. retryButtonCallback,
  3460. emailLinkListeners = null,
  3461. emailConfirmListeners = null;
  3462. /**
  3463. * set the expiration on bootstrap templates in dropdown
  3464. *
  3465. * @name TopNav.updateExpiration
  3466. * @private
  3467. * @function
  3468. * @param {Event} event
  3469. */
  3470. function updateExpiration(event) {
  3471. // get selected option
  3472. const target = event.target;
  3473. // update dropdown display and save new expiration time
  3474. const display = document.getElementById('pasteExpirationDisplay');
  3475. if (display) {
  3476. display.textContent = target.textContent;
  3477. }
  3478. pasteExpiration = target.getAttribute('data-expiration');
  3479. event.preventDefault();
  3480. }
  3481. /**
  3482. * set the format on bootstrap templates in dropdown from user interaction
  3483. *
  3484. * @name TopNav.updateFormat
  3485. * @private
  3486. * @function
  3487. * @param {Event} event
  3488. */
  3489. function updateFormat(event) {
  3490. // get selected option
  3491. const target = event.target;
  3492. // update dropdown display and save new format
  3493. const newFormat = target.getAttribute('data-format');
  3494. const display = document.getElementById('pasteFormatterDisplay');
  3495. if (display) {
  3496. display.textContent = target.textContent;
  3497. }
  3498. PasteViewer.setFormat(newFormat);
  3499. event.preventDefault();
  3500. }
  3501. /**
  3502. * when "burn after reading" is checked, disable discussion
  3503. *
  3504. * @name TopNav.changeBurnAfterReading
  3505. * @private
  3506. * @function
  3507. */
  3508. function changeBurnAfterReading() {
  3509. if (me.getBurnAfterReading()) {
  3510. if (openDiscussionOption) {
  3511. openDiscussionOption.classList.add('buttondisabled');
  3512. }
  3513. if (openDiscussion) {
  3514. openDiscussion.checked = false;
  3515. }
  3516. // if button is actually disabled, force-enable it and uncheck other button
  3517. if (burnAfterReadingOption) {
  3518. burnAfterReadingOption.classList.remove('buttondisabled');
  3519. }
  3520. } else {
  3521. if (openDiscussionOption) {
  3522. openDiscussionOption.classList.remove('buttondisabled');
  3523. }
  3524. }
  3525. }
  3526. /**
  3527. * when discussion is checked, disable "burn after reading"
  3528. *
  3529. * @name TopNav.changeOpenDiscussion
  3530. * @private
  3531. * @function
  3532. */
  3533. function changeOpenDiscussion() {
  3534. if (me.getOpenDiscussion()) {
  3535. if (burnAfterReadingOption) {
  3536. burnAfterReadingOption.classList.add('buttondisabled');
  3537. }
  3538. if (burnAfterReading) {
  3539. burnAfterReading.checked = false;
  3540. }
  3541. // if button is actually disabled, force-enable it and uncheck other button
  3542. if (openDiscussionOption) {
  3543. openDiscussionOption.classList.remove('buttondisabled');
  3544. }
  3545. } else {
  3546. if (burnAfterReadingOption) {
  3547. burnAfterReadingOption.classList.remove('buttondisabled');
  3548. }
  3549. }
  3550. }
  3551. /**
  3552. * Clear the password input in the top navigation
  3553. *
  3554. * @name TopNav.clearPasswordInput
  3555. * @function
  3556. */
  3557. function clearPasswordInput() {
  3558. if (passwordInput) {
  3559. passwordInput.value = '';
  3560. }
  3561. }
  3562. /**
  3563. * Clear the attachment input in the top navigation.
  3564. *
  3565. * @name TopNav.clearAttachmentInput
  3566. * @function
  3567. */
  3568. function clearAttachmentInput() {
  3569. // hide UI for selected files
  3570. const inputElement = fileWrap && fileWrap.querySelector('input');
  3571. if (inputElement) {
  3572. inputElement.value = '';
  3573. }
  3574. }
  3575. /**
  3576. * return raw text
  3577. *
  3578. * @name TopNav.rawText
  3579. * @private
  3580. * @function
  3581. */
  3582. function rawText() {
  3583. TopNav.hideAllButtons();
  3584. Alert.showLoading('Showing raw text…', 'time');
  3585. let paste = PasteViewer.getText();
  3586. // push a new state to allow back navigation with browser back button
  3587. history.pushState(
  3588. { type: 'raw' },
  3589. document.title,
  3590. // recreate document URL
  3591. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3592. CryptTool.base58encode(Model.getPasteKey())
  3593. );
  3594. // we use text/html instead of text/plain to avoid a bug when
  3595. // reloading the raw text view (it reverts to type text/html)
  3596. const headElements = document.head.querySelectorAll(':not(noscript):not(script):not(link[type="text/css"])');
  3597. const newDoc = document.open('text/html', 'replace');
  3598. newDoc.write('<!DOCTYPE html><html><head>');
  3599. for (let i = 0; i < headElements.length; ++i) {
  3600. newDoc.write(headElements[i].outerHTML);
  3601. }
  3602. newDoc.write(
  3603. '</head><body><pre>' +
  3604. DOMPurify.sanitize(
  3605. Helper.htmlEntities(paste),
  3606. purifyHtmlConfig
  3607. ) +
  3608. '</pre></body></html>'
  3609. );
  3610. newDoc.close();
  3611. }
  3612. /**
  3613. * download text
  3614. *
  3615. * @name TopNav.downloadText
  3616. * @private
  3617. * @function
  3618. */
  3619. function downloadText() {
  3620. const fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3621. const filename = 'document-' + Model.getPasteId() + fileFormat;
  3622. const text = PasteViewer.getText();
  3623. const element = document.createElement('a');
  3624. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3625. element.setAttribute('download', filename);
  3626. element.style.display = 'none';
  3627. document.body.appendChild(element);
  3628. element.click();
  3629. document.body.removeChild(element);
  3630. }
  3631. /**
  3632. * saves the language in a cookie and reloads the page
  3633. *
  3634. * @name TopNav.setLanguage
  3635. * @private
  3636. * @function
  3637. * @param {Event} event
  3638. */
  3639. function setLanguage(event) {
  3640. let lang = event.target.getAttribute('data-lang') || event.target.value;
  3641. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3642. window.location.reload();
  3643. event.preventDefault();
  3644. }
  3645. /**
  3646. * save the template in a cookie and reloads the page
  3647. *
  3648. * @name TopNav.setTemplate
  3649. * @private
  3650. * @function
  3651. * @param {Event} event
  3652. */
  3653. function setTemplate(event) {
  3654. let template = event.target.getAttribute('data-template') || event.target.value;
  3655. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3656. window.location.reload();
  3657. event.preventDefault();
  3658. }
  3659. /**
  3660. * hides all messages and creates a new document
  3661. *
  3662. * @name TopNav.clickNewPaste
  3663. * @private
  3664. * @function
  3665. */
  3666. function clickNewPaste() {
  3667. Controller.hideStatusMessages();
  3668. Controller.newPaste();
  3669. }
  3670. /**
  3671. * sends the document on [Ctrl]+[S] or, on macOS, [Cmd]+[S]
  3672. *
  3673. * Only acts while the send button is shown, so the browser's own
  3674. * "save page" still works when viewing an existing document.
  3675. *
  3676. * @name TopNav.sendOnShortcut
  3677. * @private
  3678. * @function
  3679. * @param {KeyboardEvent} event
  3680. */
  3681. function sendOnShortcut(event) {
  3682. // the physical S key, so non-Latin keyboard layouts work, too
  3683. const isSaveKey = event.code === 'KeyS';
  3684. // Alt is excluded because AltGr is reported as Ctrl+Alt and some
  3685. // layouts type letters with AltGr+S, Shift to leave "Save page as"
  3686. // ([Ctrl]+[Shift]+[S]) to the browser
  3687. const hasCorrectModifiers = (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey;
  3688. const isButtonAvailable = sendButton && !sendButton.classList.contains('hidden') && !sendButton.disabled;
  3689. if (isSaveKey && hasCorrectModifiers && isButtonAvailable) {
  3690. event.preventDefault();
  3691. sendButton.click();
  3692. }
  3693. }
  3694. /**
  3695. * retrys some callback registered before
  3696. *
  3697. * @name TopNav.clickRetryButton
  3698. * @private
  3699. * @function
  3700. * @param {Event} event
  3701. */
  3702. function clickRetryButton(event) {
  3703. retryButtonCallback(event);
  3704. }
  3705. /**
  3706. * removes the existing attachment
  3707. *
  3708. * @name TopNav.removeAttachment
  3709. * @private
  3710. * @function
  3711. * @param {Event} event
  3712. */
  3713. function removeAttachment(event) {
  3714. // if custom attachment is used, remove it first
  3715. if (customAttachment && !customAttachment.classList.contains('hidden')) {
  3716. AttachmentViewer.removeAttachment();
  3717. customAttachment.classList.add('hidden');
  3718. fileWrap.classList.remove('hidden');
  3719. }
  3720. // in any case, remove saved attachment data
  3721. AttachmentViewer.removeAttachmentData();
  3722. clearAttachmentInput();
  3723. AttachmentViewer.clearDragAndDrop();
  3724. // pevent '#' from appearing in the URL
  3725. event.preventDefault();
  3726. }
  3727. /**
  3728. * Shows the QR code of the current document (URL).
  3729. *
  3730. * @name TopNav.displayQrCode
  3731. * @private
  3732. * @function
  3733. */
  3734. function displayQrCode() {
  3735. const qrCanvas = kjua({
  3736. render: 'canvas',
  3737. text: window.location.href
  3738. });
  3739. const qrDisplay = document.getElementById('qrcode-display');
  3740. if (qrDisplay) {
  3741. qrDisplay.innerHTML = '';
  3742. qrDisplay.appendChild(qrCanvas);
  3743. }
  3744. }
  3745. /**
  3746. * Template Email body.
  3747. *
  3748. * @name TopNav.templateEmailBody
  3749. * @private
  3750. * @param {string} expirationDateString
  3751. * @param {bool} isBurnafterreading
  3752. */
  3753. function templateEmailBody(expirationDateString, isBurnafterreading) {
  3754. const EOL = '\n';
  3755. const BULLET = ' - ';
  3756. let emailBody = '';
  3757. if (expirationDateString !== null || isBurnafterreading) {
  3758. emailBody += I18n._('Notice:');
  3759. emailBody += EOL;
  3760. if (expirationDateString !== null) {
  3761. emailBody += EOL;
  3762. emailBody += BULLET;
  3763. // avoid DOMPurify mess with forward slash in expirationDateString
  3764. emailBody += Helper.sprintf(
  3765. I18n._(
  3766. 'This link will expire after %s.',
  3767. '%s'
  3768. ),
  3769. expirationDateString
  3770. );
  3771. }
  3772. if (isBurnafterreading) {
  3773. emailBody += EOL;
  3774. emailBody += BULLET;
  3775. emailBody += I18n._(
  3776. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3777. );
  3778. }
  3779. emailBody += EOL;
  3780. emailBody += EOL;
  3781. }
  3782. emailBody += I18n._('Link:');
  3783. emailBody += EOL;
  3784. const pasteUrlElement = document.getElementById('pasteurl');
  3785. emailBody += (pasteUrlElement && pasteUrlElement.getAttribute('href')) || window.location.href; // href is tried first as it might have been shortened
  3786. return emailBody;
  3787. }
  3788. /**
  3789. * Trigger Email send.
  3790. *
  3791. * @name TopNav.triggerEmailSend
  3792. * @private
  3793. * @param {string} subject
  3794. * @param {string} emailBody
  3795. */
  3796. function triggerEmailSend(subject, emailBody) {
  3797. window.open(
  3798. `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(emailBody)}`,
  3799. '_self',
  3800. 'noopener, noreferrer'
  3801. );
  3802. }
  3803. /**
  3804. * removes the event listeners of the e-mail confirmation dialog
  3805. *
  3806. * @name TopNav.removeEmailConfirmButtonListeners
  3807. * @private
  3808. * @function
  3809. */
  3810. function removeEmailConfirmButtonListeners() {
  3811. if (emailConfirmListeners) {
  3812. emailConfirmListeners.abort();
  3813. emailConfirmListeners = null;
  3814. }
  3815. }
  3816. /**
  3817. * removes the event listeners of the e-mail button and its dialog
  3818. *
  3819. * @name TopNav.removeEmailListeners
  3820. * @private
  3821. * @function
  3822. */
  3823. function removeEmailListeners() {
  3824. removeEmailConfirmListeners();
  3825. if (emailLinkListeners) {
  3826. emailLinkListeners.abort();
  3827. emailLinkListeners = null;
  3828. }
  3829. }
  3830. /**
  3831. * Send Email with current document (URL).
  3832. *
  3833. * @name TopNav.sendEmail
  3834. * @private
  3835. * @function
  3836. * @param {Date|null} expirationDate date of expiration
  3837. * @param {bool} isBurnafterreading whether it is burn after reading
  3838. */
  3839. function sendEmail(expirationDate, isBurnafterreading) {
  3840. const expirationDateRoundedToSecond = new Date(expirationDate);
  3841. // round down at least 30 seconds to make up for the delay of request
  3842. expirationDateRoundedToSecond.setUTCSeconds(
  3843. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3844. );
  3845. expirationDateRoundedToSecond.setUTCSeconds(0);
  3846. // reused as-is by both the confirmation-modal and direct-send paths below
  3847. const emailSubject = I18n._('Encrypted note on %s', document.title);
  3848. const emailconfirmmodal = document.getElementById('emailconfirmmodal');
  3849. if (expirationDate !== null) {
  3850. const emailconfirmTimezoneCurrent = emailconfirmmodal.querySelector('#emailconfirm-timezone-current');
  3851. const emailconfirmTimezoneUtc = emailconfirmmodal.querySelector('#emailconfirm-timezone-utc');
  3852. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3853. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip && bootstrap.Tooltip.VERSION ?
  3854. new bootstrap.Modal(emailconfirmmodal) : null;
  3855. function sendEmailAndHideModal() {
  3856. const emailBody = templateEmailBody(
  3857. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3858. expirationDateRoundedToSecond.toLocaleString(
  3859. [], localeConfiguration
  3860. ), isBurnafterreading
  3861. );
  3862. // only send once per opening of the dialog
  3863. removeEmailConfirmListeners();
  3864. if (bootstrap5EmailConfirmModal) {
  3865. bootstrap5EmailConfirmModal.hide();
  3866. }
  3867. triggerEmailSend(emailSubject, emailBody);
  3868. }
  3869. // replace the listeners of a previous opening of the dialog
  3870. removeEmailConfirmListeners();
  3871. emailConfirmListeners = new window.AbortController();
  3872. const signal = emailConfirmListeners.signal;
  3873. emailconfirmmodal.addEventListener('shown.bs.modal', () => {
  3874. emailconfirmTimezoneUtc.focus();
  3875. }, {signal});
  3876. emailconfirmTimezoneCurrent.addEventListener('click', sendEmailAndHideModal, {signal});
  3877. emailconfirmTimezoneUtc.addEventListener('click', () => {
  3878. localeConfiguration.timeZone = 'UTC';
  3879. sendEmailAndHideModal();
  3880. }, {signal});
  3881. if (bootstrap5EmailConfirmModal) {
  3882. bootstrap5EmailConfirmModal.show();
  3883. }
  3884. } else {
  3885. triggerEmailSend(emailSubject, templateEmailBody(null, isBurnafterreading));
  3886. }
  3887. }
  3888. /**
  3889. * Shows all navigation elements for viewing an existing document
  3890. *
  3891. * @name TopNav.showViewButtons
  3892. * @function
  3893. */
  3894. me.showViewButtons = function () {
  3895. if (viewButtonsDisplayed) {
  3896. return;
  3897. }
  3898. newButton.classList.remove('hidden');
  3899. cloneButton.classList.remove('hidden');
  3900. rawTextButton.classList.remove('hidden');
  3901. downloadTextButton.classList.remove('hidden');
  3902. if (qrCodeLink) {
  3903. qrCodeLink.classList.remove('hidden');
  3904. }
  3905. viewButtonsDisplayed = true;
  3906. };
  3907. /**
  3908. * Hides all navigation elements for viewing an existing document
  3909. *
  3910. * @name TopNav.hideViewButtons
  3911. * @function
  3912. */
  3913. me.hideViewButtons = function () {
  3914. if (!viewButtonsDisplayed) {
  3915. return;
  3916. }
  3917. cloneButton.classList.add('hidden');
  3918. newButton.classList.add('hidden');
  3919. rawTextButton.classList.add('hidden');
  3920. downloadTextButton.classList.add('hidden');
  3921. if (qrCodeLink) {
  3922. qrCodeLink.classList.add('hidden');
  3923. }
  3924. me.hideEmailButton();
  3925. viewButtonsDisplayed = false;
  3926. };
  3927. /**
  3928. * Hides all elements belonging to existing documents
  3929. *
  3930. * @name TopNav.hideAllButtons
  3931. * @function
  3932. */
  3933. me.hideAllButtons = function () {
  3934. me.hideViewButtons();
  3935. me.hideCreateButtons();
  3936. };
  3937. /**
  3938. * shows all elements needed when creating a new document
  3939. *
  3940. * @name TopNav.showCreateButtons
  3941. * @function
  3942. */
  3943. me.showCreateButtons = function () {
  3944. if (createButtonsDisplayed) {
  3945. return;
  3946. }
  3947. if (attach) {
  3948. attach.classList.remove('hidden');
  3949. }
  3950. burnAfterReadingOption.classList.remove('hidden');
  3951. expiration.classList.remove('hidden');
  3952. formatter.classList.remove('hidden');
  3953. newButton.classList.remove('hidden');
  3954. if (openDiscussionOption) {
  3955. openDiscussionOption.classList.remove('hidden');
  3956. }
  3957. if (password) {
  3958. password.classList.remove('hidden');
  3959. }
  3960. sendButton.classList.remove('hidden');
  3961. createButtonsDisplayed = true;
  3962. };
  3963. /**
  3964. * shows all elements needed when creating a new document
  3965. *
  3966. * @name TopNav.hideCreateButtons
  3967. * @function
  3968. */
  3969. me.hideCreateButtons = function () {
  3970. if (!createButtonsDisplayed) {
  3971. return;
  3972. }
  3973. newButton.classList.add('hidden');
  3974. sendButton.classList.add('hidden');
  3975. expiration.classList.add('hidden');
  3976. formatter.classList.add('hidden');
  3977. burnAfterReadingOption.classList.add('hidden');
  3978. if (openDiscussionOption) {
  3979. openDiscussionOption.classList.add('hidden');
  3980. }
  3981. if (password) {
  3982. password.classList.add('hidden');
  3983. }
  3984. if (attach) {
  3985. attach.classList.add('hidden');
  3986. }
  3987. createButtonsDisplayed = false;
  3988. };
  3989. /**
  3990. * only shows the "new document" button
  3991. *
  3992. * @name TopNav.showNewPasteButton
  3993. * @function
  3994. */
  3995. me.showNewPasteButton = function () {
  3996. newButton.classList.remove('hidden');
  3997. };
  3998. /**
  3999. * only shows the "retry" button
  4000. *
  4001. * @name TopNav.showRetryButton
  4002. * @function
  4003. */
  4004. me.showRetryButton = function () {
  4005. retryButton.classList.remove('hidden');
  4006. // The Bootstrap 5 template gives Retry its own list item. That item
  4007. // still takes a flex gap while only the button is hidden.
  4008. if (Helper.isBootstrap5()) {
  4009. retryButton.parentElement.classList.remove('hidden');
  4010. }
  4011. };
  4012. /**
  4013. * hides the "retry" button
  4014. *
  4015. * @name TopNav.hideRetryButton
  4016. * @function
  4017. */
  4018. me.hideRetryButton = function () {
  4019. retryButton.classList.add('hidden');
  4020. if (Helper.isBootstrap5()) {
  4021. retryButton.parentElement.classList.add('hidden');
  4022. }
  4023. };
  4024. /**
  4025. * show the "email" button
  4026. *
  4027. * @name TopNav.showEmailbutton
  4028. * @function
  4029. * @param {number|undefined} optionalRemainingTimeInSeconds
  4030. * @param {bool|undefined} optionalBurnAfterReading
  4031. */
  4032. me.showEmailButton = function (optionalRemainingTimeInSeconds, optionalBurnAfterReading) {
  4033. if (!emailLink) {
  4034. return;
  4035. }
  4036. try {
  4037. // we cache expiration date in closure to avoid inaccurate expiration datetime
  4038. const expirationDate = Helper.calculateExpirationDate(
  4039. new Date(),
  4040. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  4041. );
  4042. const isBurnafterreading = typeof optionalBurnAfterReading === 'boolean' ?
  4043. optionalBurnAfterReading : TopNav.getBurnAfterReading();
  4044. emailLink.classList.remove('hidden');
  4045. // replace the listeners of a previous document
  4046. removeEmailListeners();
  4047. emailLinkListeners = new window.AbortController();
  4048. emailLink.addEventListener('click', () => {
  4049. sendEmail(expirationDate, isBurnafterreading);
  4050. }, {signal: emailLinkListeners.signal});
  4051. } catch (error) {
  4052. console.error(error);
  4053. Alert.showError('Cannot calculate expiration date.');
  4054. }
  4055. };
  4056. /**
  4057. * hide the "email" button
  4058. *
  4059. * @name TopNav.hideEmailButton
  4060. * @function
  4061. */
  4062. me.hideEmailButton = function () {
  4063. if (!emailLink) {
  4064. return;
  4065. }
  4066. emailLink.classList.add('hidden');
  4067. removeEmailListeners();
  4068. };
  4069. /**
  4070. * only hides the clone button
  4071. *
  4072. * @name TopNav.hideCloneButton
  4073. * @function
  4074. */
  4075. me.hideCloneButton = function () {
  4076. cloneButton.classList.add('hidden');
  4077. };
  4078. /**
  4079. * only hides the raw text button
  4080. *
  4081. * @name TopNav.hideRawButton
  4082. * @function
  4083. */
  4084. me.hideRawButton = function () {
  4085. rawTextButton.classList.add('hidden');
  4086. };
  4087. /**
  4088. * only hides the download text button
  4089. *
  4090. * @name TopNav.hideRawButton
  4091. * @function
  4092. */
  4093. me.hideDownloadButton = function () {
  4094. downloadTextButton.classList.add('hidden');
  4095. };
  4096. /**
  4097. * only hides the qr code button
  4098. *
  4099. * @name TopNav.hideQrCodeButton
  4100. * @function
  4101. */
  4102. me.hideQrCodeButton = function () {
  4103. if (qrCodeLink) {
  4104. qrCodeLink.classList.add('hidden');
  4105. }
  4106. };
  4107. /**
  4108. * hide irrelevant buttons when viewing burn after reading document
  4109. *
  4110. * @name TopNav.hideBurnAfterReadingButtons
  4111. * @function
  4112. */
  4113. me.hideBurnAfterReadingButtons = function () {
  4114. me.hideCloneButton();
  4115. me.hideQrCodeButton();
  4116. me.hideEmailButton();
  4117. };
  4118. /**
  4119. * hides the file selector in attachment
  4120. *
  4121. * @name TopNav.hideFileSelector
  4122. * @function
  4123. */
  4124. me.hideFileSelector = function () {
  4125. fileWrap.classList.add('hidden');
  4126. };
  4127. /**
  4128. * shows the custom attachment
  4129. *
  4130. * @name TopNav.showCustomAttachment
  4131. * @function
  4132. */
  4133. me.showCustomAttachment = function () {
  4134. if (!customAttachment) {
  4135. return;
  4136. }
  4137. customAttachment.classList.remove('hidden');
  4138. };
  4139. /**
  4140. * hides the custom attachment
  4141. *
  4142. * @name TopNav.hideCustomAttachment
  4143. * @function
  4144. */
  4145. me.hideCustomAttachment = function () {
  4146. if (customAttachment) {
  4147. customAttachment.classList.add('hidden');
  4148. }
  4149. if (fileWrap) {
  4150. fileWrap.classList.remove('hidden');
  4151. }
  4152. };
  4153. /**
  4154. * collapses the navigation bar, only if expanded
  4155. *
  4156. * @name TopNav.collapseBar
  4157. * @function
  4158. */
  4159. me.collapseBar = function () {
  4160. const navbar = document.getElementById('navbar');
  4161. if (navbar && navbar.getAttribute('aria-expanded') === 'true') {
  4162. const toggle = document.querySelector('.navbar-toggle');
  4163. if (toggle) {
  4164. toggle.click();
  4165. }
  4166. }
  4167. };
  4168. /**
  4169. * Reset the top navigation back to it's default values.
  4170. *
  4171. * @name TopNav.resetInput
  4172. * @function
  4173. */
  4174. me.resetInput = function () {
  4175. clearAttachmentInput();
  4176. clearPasswordInput();
  4177. if (burnAfterReading) {
  4178. burnAfterReading.checked = burnAfterReadingDefault;
  4179. }
  4180. if (openDiscussion) {
  4181. openDiscussion.checked = openDiscussionDefault;
  4182. }
  4183. if (openDiscussionOption && (openDiscussionDefault || !burnAfterReadingDefault)) {
  4184. openDiscussionOption.classList.remove('buttondisabled');
  4185. }
  4186. if (burnAfterReadingDefault || !openDiscussionDefault) {
  4187. burnAfterReadingOption.classList.remove('buttondisabled');
  4188. }
  4189. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4190. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4191. if (pasteExpirationSelect) {
  4192. pasteExpirationSelect.querySelectorAll('option').forEach((option) => {
  4193. if (option.value === pasteExpiration) {
  4194. const display = document.getElementById('pasteExpirationDisplay');
  4195. if (display) {
  4196. display.textContent = option.textContent;
  4197. }
  4198. }
  4199. });
  4200. }
  4201. };
  4202. /**
  4203. * returns the currently set expiration time
  4204. *
  4205. * @name TopNav.getExpiration
  4206. * @function
  4207. * @return {int}
  4208. */
  4209. me.getExpiration = function () {
  4210. return pasteExpiration;
  4211. };
  4212. /**
  4213. * returns the currently selected file(s)
  4214. *
  4215. * @name TopNav.getFileList
  4216. * @function
  4217. * @return {FileList|null}
  4218. */
  4219. me.getFileList = function () {
  4220. const file = document.getElementById('file');
  4221. // if no file given, return null
  4222. if (!file || !file.files || !file.files.length) {
  4223. return null;
  4224. }
  4225. // ensure the selected file is still accessible
  4226. if (!file.files[0]) {
  4227. return null;
  4228. }
  4229. return file.files;
  4230. };
  4231. /**
  4232. * returns the state of the burn after reading checkbox
  4233. *
  4234. * @name TopNav.getBurnAfterReading
  4235. * @function
  4236. * @return {bool}
  4237. */
  4238. me.getBurnAfterReading = function () {
  4239. return burnAfterReading ? !!burnAfterReading.checked : false;
  4240. };
  4241. /**
  4242. * returns the state of the discussion checkbox
  4243. *
  4244. * @name TopNav.getOpenDiscussion
  4245. * @function
  4246. * @return {bool}
  4247. */
  4248. me.getOpenDiscussion = function () {
  4249. return openDiscussion ? !!openDiscussion.checked : false;
  4250. };
  4251. /**
  4252. * returns the entered password
  4253. *
  4254. * @name TopNav.getPassword
  4255. * @function
  4256. * @return {string}
  4257. */
  4258. me.getPassword = function () {
  4259. // when password is disabled passwordInput.value will return undefined
  4260. return passwordInput && passwordInput.value || '';
  4261. };
  4262. /**
  4263. * returns the element where custom attachments can be placed
  4264. *
  4265. * Used by AttachmentViewer when an attachment is cloned here.
  4266. *
  4267. * @name TopNav.getCustomAttachment
  4268. * @function
  4269. * @return {HTMLElement}
  4270. */
  4271. me.getCustomAttachment = function () {
  4272. return customAttachment;
  4273. };
  4274. /**
  4275. * Set a function to call when the retry button is clicked.
  4276. *
  4277. * @name TopNav.setRetryCallback
  4278. * @function
  4279. * @param {function} callback
  4280. */
  4281. me.setRetryCallback = function (callback) {
  4282. retryButtonCallback = callback;
  4283. };
  4284. /**
  4285. * Highlight file upload
  4286. *
  4287. * @name TopNav.highlightFileupload
  4288. * @function
  4289. */
  4290. me.highlightFileupload = function () {
  4291. // visually indicate file uploaded
  4292. const attachDropdownToggle = attach && attach.querySelector('.dropdown-toggle');
  4293. if (attachDropdownToggle && attachDropdownToggle.getAttribute('aria-expanded') === 'false') {
  4294. if (Helper.isBootstrap5()) {
  4295. new bootstrap.Dropdown(attachDropdownToggle).toggle();
  4296. } else {
  4297. attachDropdownToggle.click();
  4298. }
  4299. }
  4300. fileWrap.classList.add('highlight');
  4301. setTimeout(function () {
  4302. fileWrap.classList.remove('highlight');
  4303. }, 300);
  4304. }
  4305. /**
  4306. * set the format on bootstrap templates in dropdown programmatically
  4307. *
  4308. * @name TopNav.setFormat
  4309. * @function
  4310. */
  4311. me.setFormat = function (format) {
  4312. if (Helper.isBootstrap5()) {
  4313. const select = formatter.querySelector('select');
  4314. if (select) {
  4315. select.value = format;
  4316. }
  4317. } else {
  4318. const formatLink = formatter.parentElement.querySelector(`a[data-format="${format}"]`);
  4319. if (formatLink) {
  4320. formatLink.click();
  4321. }
  4322. }
  4323. }
  4324. /**
  4325. * returns if attachment dropdown is readonly, not editable
  4326. *
  4327. * @name TopNav.isAttachmentReadonly
  4328. * @function
  4329. * @return {bool}
  4330. */
  4331. me.isAttachmentReadonly = function () {
  4332. return !createButtonsDisplayed || (attach && attach.classList.contains('hidden'));
  4333. }
  4334. /**
  4335. * init navigation manager
  4336. *
  4337. * preloads DOM elements
  4338. *
  4339. * @name TopNav.init
  4340. * @function
  4341. */
  4342. /**
  4343. * bind all navigation event listeners
  4344. *
  4345. * @name TopNav.bindEvents
  4346. * @private
  4347. * @function
  4348. */
  4349. function bindEvents() {
  4350. const languageDropdown = document.getElementById('language');
  4351. if (languageDropdown) {
  4352. languageDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4353. link.addEventListener('click', setLanguage);
  4354. });
  4355. }
  4356. const templateDropdown = document.getElementById('template');
  4357. if (templateDropdown) {
  4358. templateDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4359. link.addEventListener('click', setTemplate);
  4360. });
  4361. }
  4362. // bind events
  4363. if (burnAfterReading) {
  4364. burnAfterReading.addEventListener('change', changeBurnAfterReading);
  4365. }
  4366. if (openDiscussionOption) {
  4367. openDiscussionOption.addEventListener('change', changeOpenDiscussion);
  4368. }
  4369. if (newButton) {
  4370. newButton.addEventListener('click', clickNewPaste);
  4371. }
  4372. if (sendButton) {
  4373. sendButton.addEventListener('click', PasteEncrypter.sendPaste);
  4374. document.addEventListener('keydown', sendOnShortcut);
  4375. }
  4376. if (cloneButton) {
  4377. cloneButton.addEventListener('click', Controller.clonePaste);
  4378. }
  4379. if (rawTextButton) {
  4380. rawTextButton.addEventListener('click', rawText);
  4381. }
  4382. if (downloadTextButton) {
  4383. downloadTextButton.addEventListener('click', downloadText);
  4384. }
  4385. if (retryButton) {
  4386. retryButton.addEventListener('click', clickRetryButton);
  4387. }
  4388. if (fileRemoveButton) {
  4389. fileRemoveButton.addEventListener('click', removeAttachment);
  4390. }
  4391. if (qrCodeLink) {
  4392. qrCodeLink.addEventListener('click', displayQrCode);
  4393. }
  4394. if (Helper.isBootstrap5()) {
  4395. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4396. if (pasteExpirationSelect) {
  4397. pasteExpirationSelect.addEventListener('change', function () {
  4398. pasteExpiration = Model.getExpirationDefault();
  4399. });
  4400. }
  4401. const pasteFormatterSelect = document.getElementById('pasteFormatter');
  4402. if (pasteFormatterSelect) {
  4403. pasteFormatterSelect.addEventListener('change', function () {
  4404. PasteViewer.setFormat(Model.getFormatDefault());
  4405. });
  4406. }
  4407. } else {
  4408. // bootstrap template drop downs
  4409. if (expiration) {
  4410. expiration.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4411. link.addEventListener('click', updateExpiration);
  4412. });
  4413. }
  4414. if (formatter) {
  4415. formatter.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4416. link.addEventListener('click', updateFormat);
  4417. });
  4418. }
  4419. // page drop downs
  4420. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4421. if (pasteExpirationSelect) {
  4422. pasteExpirationSelect.addEventListener('change', function () {
  4423. pasteExpiration = Model.getExpirationDefault();
  4424. });
  4425. }
  4426. const pasteFormatterSelect = document.getElementById('pasteFormatter');
  4427. if (pasteFormatterSelect) {
  4428. pasteFormatterSelect.addEventListener('change', function () {
  4429. PasteViewer.setFormat(Model.getFormatDefault());
  4430. });
  4431. }
  4432. }
  4433. }
  4434. me.init = function () {
  4435. attach = document.getElementById('attach');
  4436. burnAfterReading = document.getElementById('burnafterreading');
  4437. burnAfterReadingOption = document.getElementById('burnafterreadingoption');
  4438. cloneButton = document.getElementById('clonebutton');
  4439. customAttachment = document.getElementById('customattachment');
  4440. expiration = document.getElementById('expiration');
  4441. fileRemoveButton = document.getElementById('fileremovebutton');
  4442. fileWrap = document.getElementById('filewrap');
  4443. formatter = document.getElementById('formatter');
  4444. newButton = document.getElementById('newbutton');
  4445. openDiscussion = document.getElementById('opendiscussion');
  4446. openDiscussionOption = document.getElementById('opendiscussionoption');
  4447. password = document.getElementById('password');
  4448. passwordInput = document.getElementById('passwordinput');
  4449. rawTextButton = document.getElementById('rawtextbutton');
  4450. downloadTextButton = document.getElementById('downloadtextbutton');
  4451. retryButton = document.getElementById('retrybutton');
  4452. sendButton = document.getElementById('sendbutton');
  4453. qrCodeLink = document.getElementById('qrcodelink');
  4454. emailLink = document.getElementById('emaillink');
  4455. bindEvents();
  4456. // initiate default state of checkboxes
  4457. changeBurnAfterReading();
  4458. changeOpenDiscussion();
  4459. // get default values from template or fall back to set value
  4460. burnAfterReadingDefault = me.getBurnAfterReading();
  4461. openDiscussionDefault = me.getOpenDiscussion();
  4462. pasteExpiration = Model.getExpirationDefault();
  4463. createButtonsDisplayed = false;
  4464. viewButtonsDisplayed = false;
  4465. };
  4466. return me;
  4467. })(window, document);
  4468. /**
  4469. * Responsible for AJAX requests, transparently handles encryption…
  4470. *
  4471. * @name ServerInteraction
  4472. * @class
  4473. */
  4474. const ServerInteraction = (function () {
  4475. const me = {};
  4476. let successFunc = null,
  4477. failureFunc = null,
  4478. symmetricKey = null,
  4479. url,
  4480. data,
  4481. password;
  4482. /**
  4483. * public variable ('constant') for errors to prevent magic numbers
  4484. *
  4485. * @name ServerInteraction.error
  4486. * @readonly
  4487. * @enum {Object}
  4488. */
  4489. me.error = {
  4490. okay: 0,
  4491. custom: 1,
  4492. unknown: 2,
  4493. serverError: 3
  4494. };
  4495. /**
  4496. * ajaxHeaders to send in AJAX requests
  4497. *
  4498. * @name ServerInteraction.ajaxHeaders
  4499. * @private
  4500. * @readonly
  4501. * @enum {Object}
  4502. */
  4503. const ajaxHeaders = {
  4504. 'X-Requested-With': 'JSONHttpRequest',
  4505. 'Content-Type': 'application/json'
  4506. };
  4507. /**
  4508. * called after successful upload
  4509. *
  4510. * @name ServerInteraction.success
  4511. * @private
  4512. * @function
  4513. * @param {int} status
  4514. * @param {int} result - optional
  4515. */
  4516. function success(status, result) {
  4517. if (successFunc !== null) {
  4518. // add useful data to result
  4519. result.encryptionKey = symmetricKey;
  4520. successFunc(status, result);
  4521. }
  4522. }
  4523. /**
  4524. * called after a upload failure
  4525. *
  4526. * @name ServerInteraction.fail
  4527. * @private
  4528. * @function
  4529. * @param {int} status - internal code
  4530. * @param {int} result - original error code
  4531. */
  4532. function fail(status, result) {
  4533. if (failureFunc !== null) {
  4534. failureFunc(status, result);
  4535. }
  4536. }
  4537. /**
  4538. * actually uploads the data
  4539. *
  4540. * @name ServerInteraction.run
  4541. * @function
  4542. */
  4543. me.run = function () {
  4544. let isPost = Object.keys(data).length > 0,
  4545. options = {
  4546. method: isPost ? 'POST' : 'GET',
  4547. headers: ajaxHeaders
  4548. };
  4549. if (isPost) {
  4550. options.body = JSON.stringify(data);
  4551. }
  4552. fetch(url, options)
  4553. .then(response => {
  4554. if (!response.ok) {
  4555. throw response;
  4556. }
  4557. return response.json();
  4558. })
  4559. .then(result => {
  4560. if (result.status === 0) {
  4561. success(0, result);
  4562. } else if (result.status === 1) {
  4563. fail(1, result);
  4564. } else {
  4565. fail(2, result);
  4566. }
  4567. })
  4568. .catch(error => {
  4569. console.error(error);
  4570. fail(3, error);
  4571. });
  4572. };
  4573. /**
  4574. * return currently set data, used in unit testing
  4575. *
  4576. * @name ServerInteraction.getData
  4577. * @function
  4578. */
  4579. me.getData = function () {
  4580. return data;
  4581. };
  4582. /**
  4583. * set success function
  4584. *
  4585. * @name ServerInteraction.setUrl
  4586. * @function
  4587. * @param {function} newUrl
  4588. */
  4589. me.setUrl = function (newUrl) {
  4590. url = newUrl;
  4591. };
  4592. /**
  4593. * sets the password to use (first value) and optionally also the
  4594. * encryption key (not recommended, it is automatically generated).
  4595. *
  4596. * Note: Call this after prepare() as prepare() resets these values.
  4597. *
  4598. * @name ServerInteraction.setCryptValues
  4599. * @function
  4600. * @param {string} newPassword
  4601. * @param {string} newKey - optional
  4602. */
  4603. me.setCryptParameters = function (newPassword, newKey) {
  4604. password = newPassword;
  4605. if (typeof newKey !== 'undefined') {
  4606. symmetricKey = newKey;
  4607. }
  4608. };
  4609. /**
  4610. * set success function
  4611. *
  4612. * @name ServerInteraction.setSuccess
  4613. * @function
  4614. * @param {function} func
  4615. */
  4616. me.setSuccess = function (func) {
  4617. successFunc = func;
  4618. };
  4619. /**
  4620. * set failure function
  4621. *
  4622. * @name ServerInteraction.setFailure
  4623. * @function
  4624. * @param {function} func
  4625. */
  4626. me.setFailure = function (func) {
  4627. failureFunc = func;
  4628. };
  4629. /**
  4630. * prepares a new upload
  4631. *
  4632. * Call this when doing a new upload to reset any data from potential
  4633. * previous uploads. Must be called before any other method of this
  4634. * module.
  4635. *
  4636. * @name ServerInteraction.prepare
  4637. * @function
  4638. * @return {object}
  4639. */
  4640. me.prepare = function () {
  4641. // entropy should already be checked!
  4642. // reset password
  4643. password = '';
  4644. // reset key, so it a new one is generated when it is used
  4645. symmetricKey = null;
  4646. // reset data
  4647. successFunc = null;
  4648. failureFunc = null;
  4649. url = Helper.baseUri();
  4650. data = {};
  4651. };
  4652. /**
  4653. * encrypts and sets the data
  4654. *
  4655. * @name ServerInteraction.setCipherMessage
  4656. * @async
  4657. * @function
  4658. * @param {object} cipherMessage
  4659. */
  4660. me.setCipherMessage = async function (cipherMessage) {
  4661. if (
  4662. symmetricKey === null ||
  4663. (typeof symmetricKey === 'string' && symmetricKey === '')
  4664. ) {
  4665. symmetricKey = CryptTool.getSymmetricKey();
  4666. }
  4667. if (!data.hasOwnProperty('adata')) {
  4668. data['adata'] = [];
  4669. }
  4670. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4671. data['v'] = 2;
  4672. data['ct'] = cipherResult[0];
  4673. data['adata'] = cipherResult[1];
  4674. };
  4675. /**
  4676. * set the additional metadata to send unencrypted
  4677. *
  4678. * @name ServerInteraction.setUnencryptedData
  4679. * @function
  4680. * @param {string} index
  4681. * @param {mixed} element
  4682. */
  4683. me.setUnencryptedData = function (index, element) {
  4684. data[index] = element;
  4685. };
  4686. /**
  4687. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4688. *
  4689. * @name ServerInteraction.parseUploadError
  4690. * @function
  4691. * @param {int} status
  4692. * @param {object} data
  4693. * @param {string} doThisThing - a human description of the action, which was tried
  4694. * @return {array}
  4695. */
  4696. me.parseUploadError = function (status, data, doThisThing) {
  4697. let errorArray;
  4698. switch (status) {
  4699. case me.error.custom:
  4700. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4701. break;
  4702. case me.error.unknown:
  4703. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4704. break;
  4705. case me.error.serverError:
  4706. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4707. break;
  4708. default:
  4709. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4710. break;
  4711. }
  4712. return errorArray;
  4713. };
  4714. return me;
  4715. })();
  4716. /**
  4717. * (controller) Responsible for encrypting document and sending it to server.
  4718. *
  4719. * Does upload, encryption is done transparently by ServerInteraction.
  4720. *
  4721. * @name PasteEncrypter
  4722. * @class
  4723. */
  4724. const PasteEncrypter = (function () {
  4725. const me = {};
  4726. /**
  4727. * called after successful document upload
  4728. *
  4729. * @name PasteEncrypter.showCreatedPaste
  4730. * @private
  4731. * @function
  4732. * @param {int} status
  4733. * @param {object} data
  4734. */
  4735. function showCreatedPaste(status, data) {
  4736. Alert.hideLoading();
  4737. Alert.hideMessages();
  4738. // show notification
  4739. const baseUri = Helper.baseUri() + '?',
  4740. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4741. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4742. PasteStatus.createPasteNotification(url, deleteUrl);
  4743. // show new URL in browser bar
  4744. history.pushState({ type: 'newpaste' }, document.title, url);
  4745. TopNav.showViewButtons();
  4746. CopyToClipboard.setUrl(url);
  4747. CopyToClipboard.showKeyboardShortcutHint();
  4748. // this cannot be grouped with showViewButtons due to remaining time calculation
  4749. TopNav.showEmailButton();
  4750. TopNav.hideRawButton();
  4751. TopNav.hideDownloadButton();
  4752. Editor.hide();
  4753. PasteStatus.checkAutoShorten();
  4754. // parse and show text
  4755. // (preparation already done in me.sendPaste())
  4756. PasteViewer.run();
  4757. }
  4758. /**
  4759. * called after successful comment upload
  4760. *
  4761. * @name PasteEncrypter.showUploadedComment
  4762. * @private
  4763. * @function
  4764. * @param {int} status
  4765. * @param {object} data
  4766. */
  4767. function showUploadedComment(status, data) {
  4768. // show success message
  4769. Alert.showStatus('Comment posted.');
  4770. // reload document
  4771. Controller.refreshPaste(function () {
  4772. // highlight sent comment
  4773. DiscussionViewer.highlightComment(data.id, true);
  4774. // reset error handler
  4775. Alert.setCustomHandler(null);
  4776. });
  4777. }
  4778. /**
  4779. * send a reply in a discussion
  4780. *
  4781. * @name PasteEncrypter.sendComment
  4782. * @async
  4783. * @function
  4784. */
  4785. me.sendComment = async function () {
  4786. // get data
  4787. const plainText = DiscussionViewer.getReplyMessage();
  4788. // do not send if there is no data
  4789. if (plainText.length === 0) {
  4790. return;
  4791. }
  4792. let nickname = DiscussionViewer.getReplyNickname(),
  4793. parentid = DiscussionViewer.getReplyCommentId();
  4794. Alert.hideMessages();
  4795. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4796. // UI loading state
  4797. TopNav.hideAllButtons();
  4798. Alert.showLoading('Sending comment…', 'cloud-upload');
  4799. // prepare server interaction
  4800. ServerInteraction.prepare();
  4801. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4802. // set success/fail functions
  4803. ServerInteraction.setSuccess(showUploadedComment);
  4804. ServerInteraction.setFailure(function (status, data) {
  4805. // revert loading status…
  4806. Alert.hideLoading();
  4807. TopNav.showViewButtons();
  4808. // …show error message…
  4809. Alert.showError(
  4810. ServerInteraction.parseUploadError(status, data, 'post comment')
  4811. );
  4812. // …and reset error handler
  4813. Alert.setCustomHandler(null);
  4814. });
  4815. // fill it with unencrypted params
  4816. const pasteid = Model.getPasteId();
  4817. if (typeof parentid === 'undefined') {
  4818. // if parent id is not set, this is the top-most comment, so use
  4819. // document id as parent, as the root element of the discussion tree
  4820. parentid = pasteid;
  4821. }
  4822. ServerInteraction.setUnencryptedData('pasteid', pasteid);
  4823. ServerInteraction.setUnencryptedData('parentid', parentid);
  4824. // authenticate the IDs, so the comment can't be moved elsewhere
  4825. ServerInteraction.setUnencryptedData('adata', [pasteid, parentid]);
  4826. // prepare cypher message
  4827. let cipherMessage = {
  4828. 'comment': plainText
  4829. };
  4830. if (nickname.length > 0) {
  4831. cipherMessage['nickname'] = nickname;
  4832. }
  4833. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4834. ServerInteraction.run();
  4835. };
  4836. /**
  4837. * sends a new document to server
  4838. *
  4839. * @name PasteEncrypter.sendPaste
  4840. * @async
  4841. * @function
  4842. */
  4843. me.sendPaste = async function () {
  4844. // hide previous (error) messages
  4845. Controller.hideStatusMessages();
  4846. // UI loading state
  4847. TopNav.hideAllButtons();
  4848. Alert.showLoading('Sending document…', 'cloud-upload');
  4849. TopNav.collapseBar();
  4850. // get data
  4851. const plainText = Editor.getText(),
  4852. format = PasteViewer.getFormat(),
  4853. // the methods may return different values if no files are attached (null, undefined or false)
  4854. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachmentData();
  4855. // do not send if there is no data
  4856. if (plainText.length === 0 && !files) {
  4857. // revert loading status…
  4858. Alert.hideLoading();
  4859. TopNav.showCreateButtons();
  4860. return;
  4861. }
  4862. // prepare server interaction
  4863. ServerInteraction.prepare();
  4864. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4865. // set success/fail functions
  4866. ServerInteraction.setSuccess(showCreatedPaste);
  4867. ServerInteraction.setFailure(function (status, data) {
  4868. // revert loading status…
  4869. Alert.hideLoading();
  4870. TopNav.showCreateButtons();
  4871. // show error message
  4872. Alert.showError(
  4873. ServerInteraction.parseUploadError(status, data, 'create document')
  4874. );
  4875. });
  4876. // fill it with unencrypted submitted options
  4877. ServerInteraction.setUnencryptedData('adata', [
  4878. null, format,
  4879. TopNav.getOpenDiscussion() ? 1 : 0,
  4880. TopNav.getBurnAfterReading() ? 1 : 0
  4881. ]);
  4882. ServerInteraction.setUnencryptedData('meta', { 'expire': TopNav.getExpiration() });
  4883. // prepare PasteViewer for later preview
  4884. PasteViewer.setText(plainText);
  4885. PasteViewer.setFormat(format);
  4886. // prepare cypher message
  4887. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4888. cipherMessage = {
  4889. 'paste': plainText
  4890. };
  4891. if (attachmentsData.length) {
  4892. cipherMessage['attachment'] = attachmentsData;
  4893. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map(fileInfo => fileInfo.name);
  4894. } else if (AttachmentViewer.hasAttachment()) {
  4895. // fall back to cloned part
  4896. let attachments = AttachmentViewer.getAttachments();
  4897. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4898. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4899. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment, i) => {
  4900. // we need to retrieve data from blob if browser already parsed it in memory
  4901. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4902. Alert.showStatus(
  4903. [
  4904. 'Retrieving cloned file \'%s\' from memory...',
  4905. cipherMessage['attachment_name'][i]
  4906. ],
  4907. 'copy'
  4908. );
  4909. try {
  4910. const response = await fetch(attachment, {
  4911. method: 'GET',
  4912. credentials: 'omit',
  4913. signal: AbortSignal.timeout(10000)
  4914. });
  4915. if (!response.ok) {
  4916. throw new Error('HTTP ' + response.status);
  4917. }
  4918. const blobData = await response.blob();
  4919. if (blobData instanceof window.Blob) {
  4920. const fileReading = new Promise(function (resolve, reject) {
  4921. const fileReader = new FileReader();
  4922. fileReader.onload = function (event) {
  4923. resolve(event.target.result);
  4924. };
  4925. fileReader.onerror = function (error) {
  4926. reject(error);
  4927. }
  4928. fileReader.readAsDataURL(blobData);
  4929. });
  4930. return await fileReading;
  4931. } else {
  4932. const error = 'Cannot process attachment data.';
  4933. Alert.showError(error);
  4934. throw new TypeError(error);
  4935. }
  4936. } catch (error) {
  4937. Alert.showError('Cannot retrieve attachment.');
  4938. throw error;
  4939. }
  4940. }
  4941. }));
  4942. }
  4943. // encrypt message
  4944. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4945. // send data
  4946. ServerInteraction.run();
  4947. };
  4948. return me;
  4949. })();
  4950. /**
  4951. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4952. *
  4953. * Only decryption, no download.
  4954. *
  4955. * @name PasteDecrypter
  4956. * @class
  4957. */
  4958. const PasteDecrypter = (function () {
  4959. const me = {};
  4960. /**
  4961. * decrypt data or prompts for password in case of failure
  4962. *
  4963. * @name PasteDecrypter.decryptOrPromptPassword
  4964. * @private
  4965. * @async
  4966. * @function
  4967. * @param {string} key
  4968. * @param {string} password - optional, may be an empty string
  4969. * @param {string} cipherdata
  4970. * @throws {string}
  4971. * @return {Promise<false|string>} false, when unsuccessful or string (decrypted data)
  4972. */
  4973. async function decryptOrPromptPassword(key, password, cipherdata) {
  4974. // try decryption without password
  4975. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4976. // if it fails, request password
  4977. if (plaindata.length === 0 && password.length === 0) {
  4978. // show prompt
  4979. Prompt.requestPassword();
  4980. // Thus, we cannot do anything yet, we need to wait for the user
  4981. // input.
  4982. return false;
  4983. }
  4984. // if all tries failed, we can only return an error
  4985. if (plaindata.length === 0) {
  4986. return false;
  4987. }
  4988. return plaindata;
  4989. }
  4990. /**
  4991. * decrypt the actual document text
  4992. *
  4993. * @name PasteDecrypter.decryptPaste
  4994. * @private
  4995. * @async
  4996. * @function
  4997. * @param {Paste} paste - document data in object form
  4998. * @param {string} key
  4999. * @param {string} password
  5000. * @throws {string}
  5001. * @return {Promise}
  5002. */
  5003. async function decryptPaste(paste, key, password) {
  5004. const pastePlain = await decryptOrPromptPassword(
  5005. key, password,
  5006. paste.getCipherData()
  5007. );
  5008. if (pastePlain === false) {
  5009. if (password.length === 0) {
  5010. throw 'waiting on user to provide a password';
  5011. } else {
  5012. Alert.hideLoading();
  5013. // reset password, so it can be re-entered
  5014. Prompt.reset();
  5015. TopNav.showRetryButton();
  5016. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  5017. }
  5018. }
  5019. const pasteMessage = JSON.parse(pastePlain);
  5020. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  5021. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  5022. pasteMessage.attachment.forEach((attachment, key) => {
  5023. const attachment_name = pasteMessage.attachment_name[key];
  5024. AttachmentViewer.setAttachment(attachment, attachment_name);
  5025. });
  5026. } else {
  5027. // Continue to process attachment parameters as strings to ensure backward compatibility
  5028. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  5029. }
  5030. AttachmentViewer.showAttachment();
  5031. }
  5032. PasteViewer.setFormat(paste.getFormat());
  5033. PasteViewer.setText(pasteMessage.paste);
  5034. PasteViewer.run();
  5035. }
  5036. /**
  5037. * decrypts all comments and shows them
  5038. *
  5039. * @name PasteDecrypter.decryptComments
  5040. * @private
  5041. * @async
  5042. * @function
  5043. * @param {Paste} paste - document data in object form
  5044. * @param {string} key
  5045. * @param {string} password
  5046. * @return {Promise}
  5047. */
  5048. async function decryptComments(paste, key, password) {
  5049. // remove potential previous discussion
  5050. DiscussionViewer.prepareNewDiscussion();
  5051. const commentDecryptionPromises = [];
  5052. // iterate over comments
  5053. for (let i = 0; i < paste.comments.length; ++i) {
  5054. const comment = new Comment(paste.comments[i]);
  5055. paste.comments[i] = comment;
  5056. // skip comments that were moved from another document or parent
  5057. if (!comment.isBoundTo(Model.getPasteId())) {
  5058. commentDecryptionPromises.push(Promise.resolve(['', '']));
  5059. continue;
  5060. }
  5061. commentDecryptionPromises.push(
  5062. CryptTool.decipher(key, password, comment.getCipherData()).then(function (commentJson) {
  5063. const commentMessage = JSON.parse(commentJson);
  5064. return [
  5065. commentMessage.comment || '',
  5066. commentMessage.nickname || ''
  5067. ];
  5068. })
  5069. );
  5070. }
  5071. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  5072. for (let i = 0; i < paste.comments.length; ++i) {
  5073. if (plaintexts[i][0].length === 0) {
  5074. continue;
  5075. }
  5076. DiscussionViewer.addComment(
  5077. paste.comments[i],
  5078. plaintexts[i][0],
  5079. plaintexts[i][1]
  5080. );
  5081. }
  5082. });
  5083. }
  5084. /**
  5085. * show decrypted text in the display area, including discussion (if open)
  5086. *
  5087. * @name PasteDecrypter.run
  5088. * @function
  5089. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  5090. */
  5091. me.run = function (paste) {
  5092. Alert.hideMessages();
  5093. Alert.setCustomHandler(null);
  5094. Alert.showLoading('Decrypting document…', 'cloud-download');
  5095. if (typeof paste === 'undefined' || paste.type === 'click') {
  5096. // get cipher data and wait until it is available
  5097. Model.getPasteData(me.run);
  5098. return;
  5099. }
  5100. let key = Model.getPasteKey(),
  5101. password = Prompt.getPassword(),
  5102. decryptionPromises = [];
  5103. TopNav.setRetryCallback(function () {
  5104. TopNav.hideRetryButton();
  5105. me.run(paste);
  5106. });
  5107. // Clear attachments to prevent duplicates
  5108. AttachmentViewer.removeAttachment();
  5109. // decrypt paste & attachments
  5110. decryptionPromises.push(decryptPaste(paste, key, password));
  5111. // if the discussion is opened on this document, display it
  5112. if (paste.isDiscussionEnabled()) {
  5113. decryptionPromises.push(decryptComments(paste, key, password));
  5114. }
  5115. // shows the remaining time (until) deletion
  5116. PasteStatus.showRemainingTime(paste);
  5117. CopyToClipboard.showKeyboardShortcutHint();
  5118. Promise.all(decryptionPromises)
  5119. .then(() => {
  5120. Alert.hideLoading();
  5121. TopNav.showViewButtons();
  5122. // discourage cloning (it cannot really be prevented)
  5123. if (paste.isBurnAfterReadingEnabled()) {
  5124. TopNav.hideBurnAfterReadingButtons();
  5125. } else {
  5126. // we have to pass in remaining_time here
  5127. TopNav.showEmailButton(
  5128. paste.getTimeToLive(),
  5129. paste.isBurnAfterReadingEnabled()
  5130. );
  5131. }
  5132. // only offer adding comments, after document was successfully decrypted
  5133. if (paste.isDiscussionEnabled()) {
  5134. DiscussionViewer.finishDiscussion();
  5135. }
  5136. })
  5137. .catch((err) => {
  5138. // wait for the user to type in the password,
  5139. // then PasteDecrypter.run will be called again
  5140. Alert.showError(err);
  5141. });
  5142. };
  5143. return me;
  5144. })();
  5145. /**
  5146. *
  5147. * @name CopyToClipboard
  5148. * @class
  5149. */
  5150. const CopyToClipboard = (function () {
  5151. const me = {};
  5152. let copyButton,
  5153. copyLinkButton,
  5154. shortcutHint,
  5155. url;
  5156. /**
  5157. * Handle copy to clipboard button click
  5158. *
  5159. * @name CopyToClipboard.handleCopyButtonClick
  5160. * @private
  5161. * @function
  5162. */
  5163. function handleCopyButtonClick() {
  5164. if (!copyButton) return;
  5165. copyButton.addEventListener('click', function () {
  5166. const text = PasteViewer.getText();
  5167. saveToClipboard(text);
  5168. showAlertMessage('Document copied to clipboard');
  5169. });
  5170. }
  5171. /**
  5172. * Handle copy link to clipboard button click
  5173. *
  5174. * @name CopyToClipboard.handleCopyLinkButtonClick
  5175. * @private
  5176. * @function
  5177. */
  5178. function handleCopyLinkButtonClick() {
  5179. if (!copyLinkButton) return;
  5180. copyLinkButton.addEventListener('click', function () {
  5181. saveToClipboard(url);
  5182. showAlertMessage('Link copied to clipboard');
  5183. });
  5184. }
  5185. /**
  5186. * Handle CTRL+C/CMD+C keyboard shortcut
  5187. *
  5188. * @name CopyToClipboard.handleKeyboardShortcut
  5189. * @private
  5190. * @function
  5191. */
  5192. function handleKeyboardShortcut() {
  5193. document.addEventListener('copy', function () {
  5194. if (!isUserSelectedTextToCopy()) {
  5195. const text = PasteViewer.getText();
  5196. saveToClipboard(text);
  5197. showAlertMessage('Document copied to clipboard');
  5198. }
  5199. });
  5200. }
  5201. /**
  5202. * Check if user selected some text on the page to copy it
  5203. *
  5204. * @name CopyToClipboard.isUserSelectedTextToCopy
  5205. * @private
  5206. * @function
  5207. * @returns {boolean}
  5208. */
  5209. function isUserSelectedTextToCopy() {
  5210. let text = '';
  5211. if (window.getSelection) {
  5212. text = window.getSelection().toString();
  5213. } else if (document.selection && document.selection.type !== 'Control') {
  5214. text = document.selection.createRange().text;
  5215. }
  5216. return text.length > 0;
  5217. }
  5218. /**
  5219. * Save text to the clipboard
  5220. *
  5221. * @name CopyToClipboard.saveToClipboard
  5222. * @private
  5223. * @param {string} text
  5224. * @function
  5225. */
  5226. function saveToClipboard(text) {
  5227. navigator.clipboard.writeText(text);
  5228. }
  5229. /**
  5230. * Show alert message after text copy
  5231. *
  5232. * @name CopyToClipboard.showAlertMessage
  5233. * @private
  5234. * @param {string} message
  5235. * @function
  5236. */
  5237. function showAlertMessage(message) {
  5238. Alert.showStatus(message);
  5239. }
  5240. /**
  5241. * Show keyboard shortcut hint
  5242. *
  5243. * @name CopyToClipboard.showKeyboardShortcutHint
  5244. * @function
  5245. */
  5246. me.showKeyboardShortcutHint = function () {
  5247. shortcutHint.classList.remove('hidden');
  5248. };
  5249. /**
  5250. * Hide keyboard shortcut hint
  5251. *
  5252. * @name CopyToClipboard.showKeyboardShortcutHint
  5253. * @function
  5254. */
  5255. me.hideKeyboardShortcutHint = function () {
  5256. shortcutHint.classList.add('hidden');
  5257. };
  5258. /**
  5259. * Set document url
  5260. *
  5261. * @name CopyToClipboard.setUrl
  5262. * @param {string} newUrl
  5263. * @function
  5264. */
  5265. me.setUrl = function (newUrl) {
  5266. url = newUrl;
  5267. };
  5268. /**
  5269. * Initialize
  5270. *
  5271. * @name CopyToClipboard.init
  5272. * @function
  5273. */
  5274. me.init = function () {
  5275. copyButton = document.getElementById('copyShortcutHintBtn');
  5276. copyLinkButton = document.getElementById('copyLink');
  5277. shortcutHint = document.getElementById('copyShortcutHint');
  5278. handleCopyButtonClick();
  5279. handleCopyLinkButtonClick();
  5280. handleKeyboardShortcut();
  5281. };
  5282. return me;
  5283. })();
  5284. /**
  5285. *
  5286. * @name PasswordPeek
  5287. * @class
  5288. */
  5289. const PasswordPeek = (function () {
  5290. const me = {};
  5291. /**
  5292. * Switch between visible and hidden password
  5293. *
  5294. * @name PasswordPeek.handleRevealButtonClick
  5295. * @private
  5296. * @function
  5297. */
  5298. function handleRevealButtonClick() {
  5299. const element = this;
  5300. const inputGroup = element.closest('.input-group');
  5301. const passwordInput = inputGroup ? inputGroup.querySelector('.input-password') : null;
  5302. if (!passwordInput) {
  5303. return;
  5304. }
  5305. const isHidden = passwordInput.getAttribute('type') === 'password';
  5306. passwordInput.setAttribute('type', isHidden ? 'text' : 'password');
  5307. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5308. element.setAttribute('title', tooltip);
  5309. element.setAttribute('aria-label', tooltip);
  5310. // handle bootstrap 5 icons: eye & eye-slash
  5311. const buttonSvg = element.querySelector('use');
  5312. if (buttonSvg) {
  5313. const iconHref = buttonSvg.getAttribute('href');
  5314. if (iconHref) {
  5315. buttonSvg.setAttribute('href', isHidden ? `${iconHref}-slash` : iconHref.substring(0, iconHref.length - 6));
  5316. }
  5317. return;
  5318. }
  5319. // handle bootstrap 3 icons: eye-open & eye-close
  5320. const buttonSpan = element.querySelector('span');
  5321. if (buttonSpan) {
  5322. if (isHidden) {
  5323. buttonSpan.classList.add('glyphicon-eye-close');
  5324. buttonSpan.classList.remove('glyphicon-eye-open');
  5325. } else {
  5326. buttonSpan.classList.add('glyphicon-eye-open');
  5327. buttonSpan.classList.remove('glyphicon-eye-close');
  5328. }
  5329. }
  5330. }
  5331. /**
  5332. * Initialize
  5333. *
  5334. * @name PasswordPeek.init
  5335. * @function
  5336. */
  5337. me.init = function () {
  5338. const revealButton = document.querySelector('.toggle-password');
  5339. if (!revealButton) {
  5340. return;
  5341. }
  5342. revealButton.addEventListener('click', handleRevealButtonClick);
  5343. };
  5344. return me;
  5345. })();
  5346. /**
  5347. * (controller) main PrivateBin logic
  5348. *
  5349. * @name Controller
  5350. * @param {object} window
  5351. * @param {object} document
  5352. * @class
  5353. */
  5354. const Controller = (function (window, document) {
  5355. const me = {};
  5356. /**
  5357. * hides all status messages no matter which module showed them
  5358. *
  5359. * @name Controller.hideStatusMessages
  5360. * @function
  5361. */
  5362. me.hideStatusMessages = function () {
  5363. PasteStatus.hideMessages();
  5364. Alert.hideMessages();
  5365. CopyToClipboard.hideKeyboardShortcutHint();
  5366. };
  5367. /**
  5368. * creates a new document
  5369. *
  5370. * @name Controller.newPaste
  5371. * @function
  5372. */
  5373. me.newPaste = function () {
  5374. // Important: This *must not* run Alert.hideMessages() as previous
  5375. // errors from viewing a document should be shown.
  5376. TopNav.hideAllButtons();
  5377. Alert.showLoading('Preparing new document…', 'time');
  5378. PasteStatus.hideMessages();
  5379. PasteViewer.hide();
  5380. Editor.resetInput();
  5381. Editor.show();
  5382. Editor.focusInput();
  5383. AttachmentViewer.removeAttachment();
  5384. TopNav.resetInput();
  5385. // reset format
  5386. const defaultFormat = Model.getFormatDefault() || 'plaintext';
  5387. PasteViewer.setFormat(defaultFormat);
  5388. TopNav.setFormat(defaultFormat);
  5389. TopNav.showCreateButtons();
  5390. // newPaste could be called when user is on document clone editing view
  5391. TopNav.hideCustomAttachment();
  5392. AttachmentViewer.clearDragAndDrop();
  5393. AttachmentViewer.removeAttachmentData();
  5394. Alert.hideLoading();
  5395. // only push new state if we are coming from a different one
  5396. if (Helper.baseUri() !== window.location) {
  5397. history.pushState({ type: 'create' }, document.title, Helper.baseUri());
  5398. }
  5399. // clear discussion
  5400. DiscussionViewer.prepareNewDiscussion();
  5401. };
  5402. /**
  5403. * shows the loaded document
  5404. *
  5405. * @name Controller.showPaste
  5406. * @function
  5407. */
  5408. me.showPaste = function () {
  5409. try {
  5410. Model.getPasteKey();
  5411. } catch (err) {
  5412. console.error(err);
  5413. Alert.showError('Cannot decrypt document: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  5414. return;
  5415. }
  5416. // check if we should request loading confirmation
  5417. if (window.location.hash.startsWith(loadConfirmPrefix)) {
  5418. Prompt.requestLoadConfirmation();
  5419. return;
  5420. }
  5421. // show proper elements on screen
  5422. PasteDecrypter.run();
  5423. };
  5424. /**
  5425. * refreshes the loaded document to show potential new data
  5426. *
  5427. * @name Controller.refreshPaste
  5428. * @function
  5429. * @param {function} callback
  5430. */
  5431. me.refreshPaste = function (callback) {
  5432. // save window position to restore it later
  5433. const orgPosition = window.scrollY;
  5434. Model.getPasteData(function (data) {
  5435. ServerInteraction.prepare();
  5436. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5437. ServerInteraction.setFailure(function (status, data) {
  5438. // revert loading status…
  5439. Alert.hideLoading();
  5440. TopNav.showViewButtons();
  5441. // show error message
  5442. Alert.showError(
  5443. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5444. );
  5445. });
  5446. ServerInteraction.setSuccess(function (status, data) {
  5447. PasteDecrypter.run(new Paste(data));
  5448. // NOTE: callback needs to be called (with setTimeout) after a JS
  5449. // rendering cycle, as otherwise it would be called before the new content
  5450. // is actually rendered, which would cause problems when trying to e.g.
  5451. // highlight a comment right after refreshing the document, as the comment would not be in the DOM at that time.
  5452. // For scrolling, more timeout is used.
  5453. setTimeout(() => {
  5454. // restore position instantly (as the process should be instantly)
  5455. window.scrollTo({
  5456. top: orgPosition,
  5457. behavior: 'instant'
  5458. });
  5459. callback();
  5460. }, 10);
  5461. });
  5462. ServerInteraction.run();
  5463. }, false); // this false is important as it circumvents the cache
  5464. };
  5465. /**
  5466. * clone the current document
  5467. *
  5468. * @name Controller.clonePaste
  5469. * @function
  5470. */
  5471. me.clonePaste = function () {
  5472. TopNav.collapseBar();
  5473. TopNav.hideAllButtons();
  5474. // hide messages from previous document
  5475. me.hideStatusMessages();
  5476. // erase the id and the key in url
  5477. history.pushState({ type: 'clone' }, document.title, Helper.baseUri());
  5478. if (AttachmentViewer.hasAttachment()) {
  5479. const attachments = AttachmentViewer.getAttachments();
  5480. attachments.forEach(attachment => {
  5481. AttachmentViewer.moveAttachmentTo(
  5482. TopNav.getCustomAttachment(),
  5483. attachment,
  5484. 'Cloned: \'%s\''
  5485. );
  5486. });
  5487. TopNav.hideFileSelector();
  5488. AttachmentViewer.hideAttachment();
  5489. // NOTE: it also looks nice without removing the attachment
  5490. // but for a consistent display we remove it…
  5491. AttachmentViewer.hideAttachmentPreview();
  5492. TopNav.showCustomAttachment();
  5493. // show another status messages to make the user aware that the
  5494. // files were cloned too!
  5495. Alert.showStatus(
  5496. [
  5497. 'The cloned file \'%s\' was attached to this document.',
  5498. attachments.map(attachment => attachment[1]).join(', ')
  5499. ],
  5500. 'copy'
  5501. );
  5502. }
  5503. Editor.setText(PasteViewer.getText());
  5504. // also clone the format
  5505. TopNav.setFormat(PasteViewer.getFormat());
  5506. PasteViewer.hide();
  5507. Editor.show();
  5508. TopNav.showCreateButtons();
  5509. // clear discussion
  5510. DiscussionViewer.prepareNewDiscussion();
  5511. };
  5512. /**
  5513. * try initializing zlib or display a warning if it fails,
  5514. * extracted from main init to allow unit testing
  5515. *
  5516. * @name Controller.initZlib
  5517. * @function
  5518. */
  5519. me.initZlib = function () {
  5520. z = zlib.catch(function () {
  5521. if (document.body.dataset.compression !== 'none') {
  5522. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5523. }
  5524. });
  5525. };
  5526. /**
  5527. * application start
  5528. *
  5529. * @name Controller.init
  5530. * @function
  5531. */
  5532. me.init = function () {
  5533. // first load translations
  5534. I18n.loadTranslations();
  5535. // Add a hook to make all links open a new window
  5536. DOMPurify.addHook('afterSanitizeAttributes', function (node) {
  5537. // set all elements owning target to target=_blank
  5538. if ('target' in node && node.id !== 'pasteurl') {
  5539. node.setAttribute('target', '_blank');
  5540. }
  5541. // set non-HTML/MathML links to xlink:show=new
  5542. if (!node.hasAttribute('target')
  5543. && (node.hasAttribute('xlink:href')
  5544. || node.hasAttribute('href'))) {
  5545. node.setAttribute('xlink:show', 'new');
  5546. }
  5547. if ('rel' in node) {
  5548. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5549. }
  5550. });
  5551. // initialize other modules/"classes"
  5552. Alert.init();
  5553. Model.init();
  5554. AttachmentViewer.init();
  5555. DiscussionViewer.init();
  5556. Editor.init();
  5557. PasteStatus.init();
  5558. PasteViewer.init();
  5559. Prompt.init();
  5560. TopNav.init();
  5561. UiHelper.init();
  5562. CopyToClipboard.init();
  5563. PasswordPeek.init();
  5564. // check for legacy browsers before going any further
  5565. if (!Legacy.Check.getInit()) {
  5566. // Legacy check didn't complete, wait and try again
  5567. setTimeout(init, 500);
  5568. return;
  5569. }
  5570. if (!Legacy.Check.getStatus()) {
  5571. // something major is wrong, stop right away
  5572. return;
  5573. }
  5574. me.initZlib();
  5575. // if delete token is passed (i.e. document has been deleted by this
  5576. // access), add an event listener for the 'new' document button in the alert
  5577. if (Model.hasDeleteToken()) {
  5578. const newFromAlert = document.getElementById('new-from-alert');
  5579. if (newFromAlert) {
  5580. newFromAlert.addEventListener('click', function () {
  5581. UiHelper.reloadHome();
  5582. });
  5583. }
  5584. return;
  5585. }
  5586. // check whether existing document needs to be shown
  5587. try {
  5588. Model.getPasteId();
  5589. } catch (e) {
  5590. // otherwise create a new document
  5591. return me.newPaste();
  5592. }
  5593. // always reload on back button to invalidate cache (protect burn after read document)
  5594. window.addEventListener('popstate', () => {
  5595. window.location.reload();
  5596. });
  5597. // display an existing document
  5598. return me.showPaste();
  5599. };
  5600. return me;
  5601. })(window, document);
  5602. return {
  5603. Helper: Helper,
  5604. I18n: I18n,
  5605. CryptTool: CryptTool,
  5606. Model: Model,
  5607. UiHelper: UiHelper,
  5608. Alert: Alert,
  5609. PasteStatus: PasteStatus,
  5610. Prompt: Prompt,
  5611. Editor: Editor,
  5612. PasteViewer: PasteViewer,
  5613. AttachmentViewer: AttachmentViewer,
  5614. DiscussionViewer: DiscussionViewer,
  5615. TopNav: TopNav,
  5616. ServerInteraction: ServerInteraction,
  5617. PasteEncrypter: PasteEncrypter,
  5618. PasteDecrypter: PasteDecrypter,
  5619. PasswordPeek: PasswordPeek,
  5620. CopyToClipboard: CopyToClipboard,
  5621. Controller: Controller
  5622. };
  5623. })();
  5624. // main application start, called when DOM is fully loaded
  5625. // skip auto-initialization in test environments (Node.js)
  5626. if (typeof module === 'undefined' || !module.exports) {
  5627. window.addEventListener('DOMContentLoaded', function () {
  5628. // run main controller
  5629. window.PrivateBin.Controller.init();
  5630. });
  5631. }