privatebin.js 192 KB

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