privatebin.js 199 KB

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