privatebin.js 191 KB

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