privatebin.js 194 KB

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