privatebin.js 199 KB

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