privatebin.js 203 KB

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