privatebin.js 201 KB

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