privatebin.js 201 KB

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