privatebin.js 206 KB

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