privatebin.js 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @name PrivateBin
  10. * @namespace
  11. */
  12. // global Base64, DOMPurify, FileReader, 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 KB/MB/GB
  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 = 1000;
  562. const decimalPoint = 2;
  563. const sizes = [I18n._('B'), I18n._('KB'), I18n._('MB'), I18n._('GB')];
  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. let 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 = me.getAttachmentSize(attachmentData);
  2764. template.append(`(${fileName}, ${fileSize})`);
  2765. }
  2766. // sanitize SVG preview
  2767. // prevents executing embedded scripts when CSP is not set and user
  2768. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2769. // in the preview by use of an img tag, which disables scripts, too
  2770. if (mimeType.match(/^image\/.*svg/i)) {
  2771. const sanitizedData = DOMPurify.sanitize(
  2772. decodedData,
  2773. purifySvgConfig
  2774. );
  2775. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2776. }
  2777. template.removeClass('hidden');
  2778. $attachment.append(template);
  2779. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mimeType);
  2780. };
  2781. /**
  2782. * displays the attachment
  2783. *
  2784. * @name AttachmentViewer.showAttachment
  2785. * @function
  2786. */
  2787. me.showAttachment = function()
  2788. {
  2789. // skip, if attachments got disabled
  2790. if (!$attachment || !$attachmentPreview) return;
  2791. $attachment.removeClass('hidden');
  2792. if (me.hasAttachmentPreview()) {
  2793. $attachmentPreview.removeClass('hidden');
  2794. }
  2795. };
  2796. /**
  2797. * removes the attachment
  2798. *
  2799. * This automatically hides the attachment containers too, to
  2800. * prevent an inconsistent display.
  2801. *
  2802. * @name AttachmentViewer.removeAttachment
  2803. * @function
  2804. */
  2805. me.removeAttachment = function()
  2806. {
  2807. if (!$attachment.length) {
  2808. return;
  2809. }
  2810. me.hideAttachment();
  2811. me.hideAttachmentPreview();
  2812. $attachment.html('');
  2813. $attachmentPreview.html('');
  2814. $dragAndDropFileNames.html('');
  2815. AttachmentViewer.removeAttachmentData();
  2816. };
  2817. /**
  2818. * removes the attachment data
  2819. *
  2820. * This removes the data, which would be uploaded otherwise.
  2821. *
  2822. * @name AttachmentViewer.removeAttachmentData
  2823. * @function
  2824. */
  2825. me.removeAttachmentData = function()
  2826. {
  2827. files = undefined;
  2828. attachmentsData = [];
  2829. };
  2830. /**
  2831. * Cleares the drag & drop data.
  2832. *
  2833. * @name AttachmentViewer.clearDragAndDrop
  2834. * @function
  2835. */
  2836. me.clearDragAndDrop = function()
  2837. {
  2838. $dragAndDropFileNames.html('');
  2839. };
  2840. /**
  2841. * Print file names added via drag & drop
  2842. *
  2843. * @name AttachmentViewer.printDragAndDropFileNames
  2844. * @private
  2845. * @function
  2846. * @param {array} fileNames
  2847. */
  2848. function printDragAndDropFileNames(fileNames) {
  2849. $dragAndDropFileNames.html(fileNames.join("<br>"));
  2850. }
  2851. /**
  2852. * hides the attachment
  2853. *
  2854. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2855. * for that) nor will it hide the attachment link if it was moved somewhere
  2856. * else (see AttachmentViewer.moveAttachmentTo).
  2857. *
  2858. * @name AttachmentViewer.hideAttachment
  2859. * @function
  2860. */
  2861. me.hideAttachment = function()
  2862. {
  2863. $attachment.addClass('hidden');
  2864. };
  2865. /**
  2866. * hides the attachment preview
  2867. *
  2868. * @name AttachmentViewer.hideAttachmentPreview
  2869. * @function
  2870. */
  2871. me.hideAttachmentPreview = function()
  2872. {
  2873. if ($attachmentPreview) {
  2874. $attachmentPreview.addClass('hidden');
  2875. }
  2876. };
  2877. /**
  2878. * checks if has any attachment preview
  2879. *
  2880. * @name AttachmentViewer.hasAttachmentPreview
  2881. * @function
  2882. * @return {JQuery}
  2883. */
  2884. me.hasAttachmentPreview = function()
  2885. {
  2886. return $attachmentPreview.children().length > 0;
  2887. }
  2888. /**
  2889. * checks if there is an attachment displayed
  2890. *
  2891. * @name AttachmentViewer.hasAttachment
  2892. * @function
  2893. */
  2894. me.hasAttachment = function()
  2895. {
  2896. if (!$attachment.length) {
  2897. return false;
  2898. }
  2899. return [...$attachment.children()].length > 0;
  2900. };
  2901. /**
  2902. * checks if there is attachment data (for preview!) available
  2903. *
  2904. * It returns true, when there is data that needs to be encrypted.
  2905. *
  2906. * @name AttachmentViewer.hasAttachmentData
  2907. * @function
  2908. */
  2909. me.hasAttachmentData = function()
  2910. {
  2911. if ($attachment.length) {
  2912. return true;
  2913. }
  2914. return false;
  2915. };
  2916. /**
  2917. * return the attachments
  2918. *
  2919. * @name AttachmentViewer.getAttachments
  2920. * @function
  2921. * @returns {array}
  2922. */
  2923. me.getAttachments = function()
  2924. {
  2925. return [...$attachment.find('a')].map(link => (
  2926. [
  2927. $(link).prop('href'),
  2928. $(link).prop('download')
  2929. ]
  2930. ));
  2931. };
  2932. /**
  2933. * Get attachment mime type
  2934. *
  2935. * @name AttachmentViewer.getAttachmentMimeType
  2936. * @function
  2937. * @param {string} attachmentData - Base64 string
  2938. */
  2939. me.getAttachmentMimeType = function(attachmentData)
  2940. {
  2941. // position in data URI string of where mimeType ends
  2942. const mimeTypeEnd = attachmentData.indexOf(';');
  2943. // extract mimeType
  2944. return attachmentData.substring(5, mimeTypeEnd);
  2945. }
  2946. /**
  2947. * Get attachment size in B/KB/MB/GB
  2948. *
  2949. * @name AttachmentViewer.getAttachmentSize
  2950. * @function
  2951. * @param {string} attachmentData - Base64 string
  2952. */
  2953. me.getAttachmentSize = function(attachmentData)
  2954. {
  2955. const base64Start = attachmentData.indexOf(',') + 1;
  2956. const rawData = attachmentData.substring(base64Start);
  2957. const decodedData = rawData.length > 0 ? atob(rawData) : '';
  2958. const buf = new Uint8Array(decodedData.length);
  2959. const bytes = new Blob([buf]).size;
  2960. return Helper.formatBytes(bytes);
  2961. }
  2962. /**
  2963. * moves the attachment link to another element
  2964. *
  2965. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2966. *
  2967. * @name AttachmentViewer.moveAttachmentTo
  2968. * @function
  2969. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2970. * @param {array} attachment - attachment data
  2971. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2972. */
  2973. me.moveAttachmentTo = function($element, attachment, label)
  2974. {
  2975. const attachmentLink = $(document.createElement('a'))
  2976. .addClass('alert-link')
  2977. .prop('href', attachment[0])
  2978. .prop('download', attachment[1]);
  2979. // move elemement to new place
  2980. attachmentLink.appendTo($element);
  2981. // update text - ensuring no HTML is inserted into the text node
  2982. I18n._(attachmentLink, label, attachment[1]);
  2983. };
  2984. /**
  2985. * read files data as data URL using the FileReader API
  2986. *
  2987. * @name AttachmentViewer.readFileData
  2988. * @private
  2989. * @function
  2990. * @param {FileList[]} loadedFiles (optional) loaded files array
  2991. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2992. */
  2993. function readFileData(loadedFiles) {
  2994. if (typeof FileReader === 'undefined') {
  2995. // revert loading status…
  2996. me.hideAttachment();
  2997. me.hideAttachmentPreview();
  2998. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2999. return;
  3000. }
  3001. if (loadedFiles === undefined) {
  3002. loadedFiles = [...$fileInput[0].files];
  3003. me.clearDragAndDrop();
  3004. } else {
  3005. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  3006. printDragAndDropFileNames(fileNames);
  3007. }
  3008. if (typeof loadedFiles !== 'undefined') {
  3009. files = loadedFiles;
  3010. loadedFiles.forEach(loadedFile => {
  3011. const fileReader = new FileReader();
  3012. fileReader.onload = function (event) {
  3013. const dataURL = event.target.result;
  3014. if (dataURL) {
  3015. attachmentsData.push(dataURL);
  3016. }
  3017. if (Editor.isPreview()) {
  3018. me.handleAttachmentPreview($attachmentPreview, dataURL);
  3019. $attachmentPreview.removeClass('hidden');
  3020. }
  3021. TopNav.highlightFileupload();
  3022. };
  3023. fileReader.readAsDataURL(loadedFile);
  3024. });
  3025. } else {
  3026. me.removeAttachmentData();
  3027. }
  3028. }
  3029. /**
  3030. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  3031. *
  3032. * @name AttachmentViewer.handleBlobAttachmentPreview
  3033. * @function
  3034. * @argument {jQuery} $targetElement element where the preview should be appended
  3035. * @argument {string} file as a blob URL
  3036. * @argument {string} mime type
  3037. */
  3038. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  3039. const alreadyIncludesCurrentAttachment = $targetElement.find(`[src='${blobUrl}']`).length > 0;
  3040. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  3041. if (mimeType.match(/^image\//i)) {
  3042. $targetElement.append(
  3043. $(document.createElement('img'))
  3044. .attr('src', blobUrl)
  3045. .attr('class', 'img-thumbnail')
  3046. );
  3047. } else if (mimeType.match(/^video\//i)) {
  3048. $targetElement.append(
  3049. $(document.createElement('video'))
  3050. .attr('controls', 'true')
  3051. .attr('autoplay', 'true')
  3052. .attr('class', 'img-thumbnail')
  3053. .append($(document.createElement('source'))
  3054. .attr('type', mimeType)
  3055. .attr('src', blobUrl))
  3056. );
  3057. } else if (mimeType.match(/^audio\//i)) {
  3058. $targetElement.append(
  3059. $(document.createElement('audio'))
  3060. .attr('controls', 'true')
  3061. .attr('autoplay', 'true')
  3062. .append($(document.createElement('source'))
  3063. .attr('type', mimeType)
  3064. .attr('src', blobUrl))
  3065. );
  3066. } else if (mimeType.match(/\/pdf/i)) {
  3067. // Fallback for browsers, that don't support the vh unit
  3068. const clientHeight = $(window).height();
  3069. $targetElement.append(
  3070. $(document.createElement('embed'))
  3071. .attr('src', blobUrl)
  3072. .attr('type', 'application/pdf')
  3073. .attr('class', 'pdfPreview')
  3074. .css('height', clientHeight)
  3075. );
  3076. }
  3077. }
  3078. };
  3079. /**
  3080. * attaches the file attachment drag & drop handler to the page
  3081. *
  3082. * @name AttachmentViewer.addDragDropHandler
  3083. * @private
  3084. * @function
  3085. */
  3086. function addDragDropHandler() {
  3087. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  3088. return;
  3089. }
  3090. const handleDragEnterOrOver = function(event) {
  3091. event.stopPropagation();
  3092. event.preventDefault();
  3093. return false;
  3094. };
  3095. const handleDrop = function(event) {
  3096. const evt = event.originalEvent;
  3097. evt.stopPropagation();
  3098. evt.preventDefault();
  3099. if (TopNav.isAttachmentReadonly()) {
  3100. return false;
  3101. }
  3102. if ($fileInput) {
  3103. const files = [...evt.dataTransfer.files];
  3104. //Clear the file input:
  3105. $fileInput.wrap('<form>').closest('form').get(0).reset();
  3106. $fileInput.unwrap();
  3107. //Only works in Chrome:
  3108. //fileInput[0].files = e.dataTransfer.files;
  3109. readFileData(files);
  3110. }
  3111. };
  3112. $(document).draghover().on({
  3113. 'draghoverstart': function(e) {
  3114. if (TopNav.isAttachmentReadonly()) {
  3115. e.stopPropagation();
  3116. e.preventDefault();
  3117. return false;
  3118. }
  3119. // show dropzone to indicate drop support
  3120. $dropzone.removeClass('hidden');
  3121. },
  3122. 'draghoverend': function() {
  3123. $dropzone.addClass('hidden');
  3124. }
  3125. });
  3126. $(document).on('drop', handleDrop);
  3127. $(document).on('dragenter dragover', handleDragEnterOrOver);
  3128. $fileInput.on('change', function () {
  3129. readFileData();
  3130. });
  3131. }
  3132. /**
  3133. * attaches the clipboard attachment handler to the page
  3134. *
  3135. * @name AttachmentViewer.addClipboardEventHandler
  3136. * @private
  3137. * @function
  3138. */
  3139. function addClipboardEventHandler() {
  3140. $(document).on('paste', function (event) {
  3141. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3142. const lastItem = items[items.length - 1];
  3143. if (lastItem.kind === 'file') {
  3144. if (TopNav.isAttachmentReadonly()) {
  3145. event.stopPropagation();
  3146. event.preventDefault();
  3147. return false;
  3148. } else {
  3149. readFileData(lastItem.getAsFile());
  3150. }
  3151. }
  3152. });
  3153. }
  3154. /**
  3155. * getter for attachment data
  3156. *
  3157. * @name AttachmentViewer.getAttachmentsData
  3158. * @function
  3159. * @return {string[]}
  3160. */
  3161. me.getAttachmentsData = function () {
  3162. return attachmentsData;
  3163. };
  3164. /**
  3165. * getter for attachment preview
  3166. *
  3167. * @name AttachmentViewer.getAttachmentPreview
  3168. * @function
  3169. * @return {jQuery}
  3170. */
  3171. me.getAttachmentPreview = function () {
  3172. return $attachmentPreview;
  3173. };
  3174. /**
  3175. * getter for files data, returns the file list
  3176. *
  3177. * @name AttachmentViewer.getFiles
  3178. * @function
  3179. * @return {FileList[]}
  3180. */
  3181. me.getFiles = function () {
  3182. return files;
  3183. };
  3184. /**
  3185. * initiate
  3186. *
  3187. * preloads jQuery elements
  3188. *
  3189. * @name AttachmentViewer.init
  3190. * @function
  3191. */
  3192. me.init = function()
  3193. {
  3194. $attachment = $('#attachment');
  3195. $dragAndDropFileNames = $('#dragAndDropFileName');
  3196. $dropzone = $('#dropzone');
  3197. if($attachment.length) {
  3198. $attachmentPreview = $('#attachmentPreview');
  3199. $fileInput = $('#file');
  3200. addDragDropHandler();
  3201. addClipboardEventHandler();
  3202. }
  3203. }
  3204. return me;
  3205. })();
  3206. /**
  3207. * (view) Shows discussion thread and handles replies
  3208. *
  3209. * @name DiscussionViewer
  3210. * @class
  3211. */
  3212. const DiscussionViewer = (function () {
  3213. const me = {};
  3214. let $commentTail,
  3215. $discussion,
  3216. $reply,
  3217. $replyMessage,
  3218. $replyNickname,
  3219. $replyStatus,
  3220. $commentContainer,
  3221. replyCommentId;
  3222. /**
  3223. * initializes the templates
  3224. *
  3225. * @name DiscussionViewer.initTemplates
  3226. * @private
  3227. * @function
  3228. */
  3229. function initTemplates()
  3230. {
  3231. $reply = Model.getTemplate('reply');
  3232. $replyMessage = $reply.find('#replymessage');
  3233. $replyNickname = $reply.find('#nickname');
  3234. $replyStatus = $reply.find('#replystatus');
  3235. // cache jQuery elements
  3236. $commentTail = Model.getTemplate('commenttail');
  3237. }
  3238. /**
  3239. * open the comment entry when clicking the "Reply" button of a comment
  3240. *
  3241. * @name DiscussionViewer.openReply
  3242. * @private
  3243. * @function
  3244. * @param {Event} event
  3245. */
  3246. function openReply(event)
  3247. {
  3248. const $source = $(event.target);
  3249. // show all reply buttons
  3250. $commentContainer.find('button').removeClass('hidden');
  3251. // hide the current reply button
  3252. $source.addClass('hidden');
  3253. // clear input
  3254. $replyMessage.val('');
  3255. $replyNickname.val('');
  3256. // get comment id from source element
  3257. replyCommentId = $source.parent().prop('id').split('_')[1];
  3258. // move to correct position
  3259. $source.after($reply);
  3260. // show
  3261. $reply.removeClass('hidden');
  3262. $replyMessage.focus();
  3263. event.preventDefault();
  3264. }
  3265. /**
  3266. * custom handler for displaying notifications in own status message area
  3267. *
  3268. * @name DiscussionViewer.handleNotification
  3269. * @function
  3270. * @param {string} alertType
  3271. * @return {bool|jQuery}
  3272. */
  3273. me.handleNotification = function(alertType)
  3274. {
  3275. // ignore loading messages
  3276. if (alertType === 'loading') {
  3277. return false;
  3278. }
  3279. if (alertType === 'danger') {
  3280. $replyStatus.removeClass('alert-info');
  3281. $replyStatus.addClass('alert-danger');
  3282. $replyStatus.find(':first').removeClass('glyphicon-alert');
  3283. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  3284. } else {
  3285. $replyStatus.removeClass('alert-danger');
  3286. $replyStatus.addClass('alert-info');
  3287. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  3288. $replyStatus.find(':first').addClass('glyphicon-alert');
  3289. }
  3290. return $replyStatus;
  3291. };
  3292. /**
  3293. * adds another comment
  3294. *
  3295. * @name DiscussionViewer.addComment
  3296. * @function
  3297. * @param {Comment} comment
  3298. * @param {string} commentText
  3299. * @param {string} nickname
  3300. */
  3301. me.addComment = function(comment, commentText, nickname)
  3302. {
  3303. if (commentText === '') {
  3304. commentText = 'comment decryption failed';
  3305. }
  3306. // create new comment based on template
  3307. const $commentEntry = Model.getTemplate('comment');
  3308. $commentEntry.prop('id', 'comment_' + comment.id);
  3309. const $commentEntryData = $commentEntry.find('div.commentdata');
  3310. // set & parse text
  3311. $commentEntryData.text(commentText);
  3312. Helper.urls2links($commentEntryData);
  3313. // set nickname
  3314. if (nickname.length > 0) {
  3315. $commentEntry.find('span.nickname').text(nickname);
  3316. } else {
  3317. $commentEntry.find('span.nickname').html('<i></i>');
  3318. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  3319. }
  3320. // set date
  3321. const created = comment.getCreated();
  3322. const commentDate = created == 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3323. $commentEntry.find('span.commentdate')
  3324. .text(commentDate)
  3325. .attr('title', 'CommentID: ' + comment.id);
  3326. // if an avatar is available, display it
  3327. const icon = comment.getIcon();
  3328. if (icon) {
  3329. $commentEntry.find('span.nickname')
  3330. .before(
  3331. '<img src="' + icon + '" class="vizhash" /> '
  3332. );
  3333. $(document).on('languageLoaded', function () {
  3334. $commentEntry.find('img.vizhash')
  3335. .prop('title', I18n._('Avatar generated from IP address'));
  3336. });
  3337. }
  3338. // starting point (default value/fallback)
  3339. let $place = $commentContainer;
  3340. // if parent comment exists
  3341. const $parentComment = $('#comment_' + comment.parentid);
  3342. if ($parentComment.length) {
  3343. // use parent as position for new comment, so it is shifted
  3344. // to the right
  3345. $place = $parentComment;
  3346. }
  3347. // finally append comment
  3348. $place.append($commentEntry);
  3349. };
  3350. /**
  3351. * finishes the discussion area after last comment
  3352. *
  3353. * @name DiscussionViewer.finishDiscussion
  3354. * @function
  3355. */
  3356. me.finishDiscussion = function()
  3357. {
  3358. // add 'add new comment' area
  3359. $commentContainer.append($commentTail);
  3360. // show discussions
  3361. $discussion.removeClass('hidden');
  3362. };
  3363. /**
  3364. * removes the old discussion and prepares everything for creating a new
  3365. * one.
  3366. *
  3367. * @name DiscussionViewer.prepareNewDiscussion
  3368. * @function
  3369. */
  3370. me.prepareNewDiscussion = function()
  3371. {
  3372. $commentContainer.html('');
  3373. $discussion.addClass('hidden');
  3374. // (re-)init templates
  3375. initTemplates();
  3376. };
  3377. /**
  3378. * returns the users message from the reply form
  3379. *
  3380. * @name DiscussionViewer.getReplyMessage
  3381. * @function
  3382. * @return {String}
  3383. */
  3384. me.getReplyMessage = function()
  3385. {
  3386. return $replyMessage.val();
  3387. };
  3388. /**
  3389. * returns the users nickname (if any) from the reply form
  3390. *
  3391. * @name DiscussionViewer.getReplyNickname
  3392. * @function
  3393. * @return {String}
  3394. */
  3395. me.getReplyNickname = function()
  3396. {
  3397. return $replyNickname.val();
  3398. };
  3399. /**
  3400. * returns the id of the parent comment the user is replying to
  3401. *
  3402. * @name DiscussionViewer.getReplyCommentId
  3403. * @function
  3404. * @return {int|undefined}
  3405. */
  3406. me.getReplyCommentId = function()
  3407. {
  3408. return replyCommentId;
  3409. };
  3410. /**
  3411. * highlights a specific comment and scrolls to it if necessary
  3412. *
  3413. * @name DiscussionViewer.highlightComment
  3414. * @function
  3415. * @param {string} commentId
  3416. * @param {bool} fadeOut - whether to fade out the comment
  3417. */
  3418. me.highlightComment = function(commentId, fadeOut)
  3419. {
  3420. const $comment = $('#comment_' + commentId);
  3421. // in case comment does not exist, cancel
  3422. if ($comment.length === 0) {
  3423. return;
  3424. }
  3425. $comment.addClass('highlight');
  3426. const highlightComment = function () {
  3427. if (fadeOut === true) {
  3428. setTimeout(function () {
  3429. $comment.removeClass('highlight');
  3430. }, 300);
  3431. }
  3432. };
  3433. if (UiHelper.isVisible($comment)) {
  3434. return highlightComment();
  3435. }
  3436. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  3437. };
  3438. /**
  3439. * initiate
  3440. *
  3441. * preloads jQuery elements
  3442. *
  3443. * @name DiscussionViewer.init
  3444. * @function
  3445. */
  3446. me.init = function()
  3447. {
  3448. // bind events to templates (so they are later cloned)
  3449. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  3450. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  3451. $commentContainer = $('#commentcontainer');
  3452. $discussion = $('#discussion');
  3453. };
  3454. return me;
  3455. })();
  3456. /**
  3457. * Manage top (navigation) bar
  3458. *
  3459. * @name TopNav
  3460. * @param {object} window
  3461. * @param {object} document
  3462. * @class
  3463. */
  3464. const TopNav = (function (window, document) {
  3465. const me = {};
  3466. let createButtonsDisplayed = false,
  3467. viewButtonsDisplayed = false,
  3468. burnAfterReadingDefault = false,
  3469. openDiscussionDefault = false,
  3470. $attach,
  3471. $burnAfterReading,
  3472. $burnAfterReadingOption,
  3473. $cloneButton,
  3474. $customAttachment,
  3475. $expiration,
  3476. $fileRemoveButton,
  3477. $fileWrap,
  3478. $formatter,
  3479. $newButton,
  3480. $openDiscussion,
  3481. $openDiscussionOption,
  3482. $password,
  3483. $passwordInput,
  3484. $rawTextButton,
  3485. $downloadTextButton,
  3486. $qrCodeLink,
  3487. $emailLink,
  3488. $sendButton,
  3489. $retryButton,
  3490. pasteExpiration = null,
  3491. retryButtonCallback;
  3492. /**
  3493. * set the expiration on bootstrap templates in dropdown
  3494. *
  3495. * @name TopNav.updateExpiration
  3496. * @private
  3497. * @function
  3498. * @param {Event} event
  3499. */
  3500. function updateExpiration(event)
  3501. {
  3502. // get selected option
  3503. const target = $(event.target);
  3504. // update dropdown display and save new expiration time
  3505. $('#pasteExpirationDisplay').text(target.text());
  3506. pasteExpiration = target.data('expiration');
  3507. event.preventDefault();
  3508. }
  3509. /**
  3510. * set the format on bootstrap templates in dropdown from user interaction
  3511. *
  3512. * @name TopNav.updateFormat
  3513. * @private
  3514. * @function
  3515. * @param {Event} event
  3516. */
  3517. function updateFormat(event)
  3518. {
  3519. // get selected option
  3520. const $target = $(event.target);
  3521. // update dropdown display and save new format
  3522. const newFormat = $target.data('format');
  3523. $('#pasteFormatterDisplay').text($target.text());
  3524. PasteViewer.setFormat(newFormat);
  3525. event.preventDefault();
  3526. }
  3527. /**
  3528. * when "burn after reading" is checked, disable discussion
  3529. *
  3530. * @name TopNav.changeBurnAfterReading
  3531. * @private
  3532. * @function
  3533. */
  3534. function changeBurnAfterReading()
  3535. {
  3536. if (me.getBurnAfterReading()) {
  3537. $openDiscussionOption.addClass('buttondisabled');
  3538. $openDiscussion.prop('checked', false);
  3539. // if button is actually disabled, force-enable it and uncheck other button
  3540. $burnAfterReadingOption.removeClass('buttondisabled');
  3541. } else {
  3542. $openDiscussionOption.removeClass('buttondisabled');
  3543. }
  3544. }
  3545. /**
  3546. * when discussion is checked, disable "burn after reading"
  3547. *
  3548. * @name TopNav.changeOpenDiscussion
  3549. * @private
  3550. * @function
  3551. */
  3552. function changeOpenDiscussion()
  3553. {
  3554. if (me.getOpenDiscussion()) {
  3555. $burnAfterReadingOption.addClass('buttondisabled');
  3556. $burnAfterReading.prop('checked', false);
  3557. // if button is actually disabled, force-enable it and uncheck other button
  3558. $openDiscussionOption.removeClass('buttondisabled');
  3559. } else {
  3560. $burnAfterReadingOption.removeClass('buttondisabled');
  3561. }
  3562. }
  3563. /**
  3564. * Clear the password input in the top navigation
  3565. *
  3566. * @name TopNav.clearPasswordInput
  3567. * @function
  3568. */
  3569. function clearPasswordInput()
  3570. {
  3571. $passwordInput.val('');
  3572. }
  3573. /**
  3574. * Clear the attachment input in the top navigation.
  3575. *
  3576. * @name TopNav.clearAttachmentInput
  3577. * @function
  3578. */
  3579. function clearAttachmentInput()
  3580. {
  3581. // hide UI for selected files
  3582. // our up-to-date jQuery can handle it :)
  3583. $fileWrap.find('input').val('');
  3584. }
  3585. /**
  3586. * return raw text
  3587. *
  3588. * @name TopNav.rawText
  3589. * @private
  3590. * @function
  3591. */
  3592. function rawText()
  3593. {
  3594. TopNav.hideAllButtons();
  3595. Alert.showLoading('Showing raw text…', 'time');
  3596. let paste = PasteViewer.getText();
  3597. // push a new state to allow back navigation with browser back button
  3598. history.pushState(
  3599. {type: 'raw'},
  3600. document.title,
  3601. // recreate paste URL
  3602. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3603. CryptTool.base58encode(Model.getPasteKey())
  3604. );
  3605. // we use text/html instead of text/plain to avoid a bug when
  3606. // reloading the raw text view (it reverts to type text/html)
  3607. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3608. newDoc = document.open('text/html', 'replace');
  3609. newDoc.write('<!DOCTYPE html><html><head>');
  3610. for (let i = 0; i < $head.length; ++i) {
  3611. newDoc.write($head[i].outerHTML);
  3612. }
  3613. newDoc.write(
  3614. '</head><body><pre>' +
  3615. DOMPurify.sanitize(
  3616. Helper.htmlEntities(paste),
  3617. purifyHtmlConfig
  3618. ) +
  3619. '</pre></body></html>'
  3620. );
  3621. newDoc.close();
  3622. }
  3623. /**
  3624. * download text
  3625. *
  3626. * @name TopNav.downloadText
  3627. * @private
  3628. * @function
  3629. */
  3630. function downloadText()
  3631. {
  3632. var fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3633. var filename='paste-' + Model.getPasteId() + fileFormat;
  3634. var text = PasteViewer.getText();
  3635. var element = document.createElement('a');
  3636. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3637. element.setAttribute('download', filename);
  3638. element.style.display = 'none';
  3639. document.body.appendChild(element);
  3640. element.click();
  3641. document.body.removeChild(element);
  3642. }
  3643. /**
  3644. * saves the language in a cookie and reloads the page
  3645. *
  3646. * @name TopNav.setLanguage
  3647. * @private
  3648. * @function
  3649. * @param {Event} event
  3650. */
  3651. function setLanguage(event)
  3652. {
  3653. let lang = $(event.target).data('lang') || event.target.value;
  3654. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3655. window.location.reload();
  3656. event.preventDefault();
  3657. }
  3658. /**
  3659. * save the template in a cookie and reloads the page
  3660. *
  3661. * @name TopNav.setTemplate
  3662. * @private
  3663. * @function
  3664. * @param {Event} event
  3665. */
  3666. function setTemplate(event)
  3667. {
  3668. let template = $(event.target).data('template') || event.target.value;
  3669. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3670. window.location.reload();
  3671. event.preventDefault();
  3672. }
  3673. /**
  3674. * hides all messages and creates a new paste
  3675. *
  3676. * @name TopNav.clickNewPaste
  3677. * @private
  3678. * @function
  3679. */
  3680. function clickNewPaste()
  3681. {
  3682. Controller.hideStatusMessages();
  3683. Controller.newPaste();
  3684. }
  3685. /**
  3686. * retrys some callback registered before
  3687. *
  3688. * @name TopNav.clickRetryButton
  3689. * @private
  3690. * @function
  3691. * @param {Event} event
  3692. */
  3693. function clickRetryButton(event)
  3694. {
  3695. retryButtonCallback(event);
  3696. }
  3697. /**
  3698. * removes the existing attachment
  3699. *
  3700. * @name TopNav.removeAttachment
  3701. * @private
  3702. * @function
  3703. * @param {Event} event
  3704. */
  3705. function removeAttachment(event)
  3706. {
  3707. // if custom attachment is used, remove it first
  3708. if (!$customAttachment.hasClass('hidden')) {
  3709. AttachmentViewer.removeAttachment();
  3710. $customAttachment.addClass('hidden');
  3711. $fileWrap.removeClass('hidden');
  3712. }
  3713. // in any case, remove saved attachment data
  3714. AttachmentViewer.removeAttachmentData();
  3715. clearAttachmentInput();
  3716. AttachmentViewer.clearDragAndDrop();
  3717. // pevent '#' from appearing in the URL
  3718. event.preventDefault();
  3719. }
  3720. /**
  3721. * Shows the QR code of the current paste (URL).
  3722. *
  3723. * @name TopNav.displayQrCode
  3724. * @private
  3725. * @function
  3726. */
  3727. function displayQrCode()
  3728. {
  3729. const qrCanvas = kjua({
  3730. render: 'canvas',
  3731. text: window.location.href
  3732. });
  3733. $('#qrcode-display').html(qrCanvas);
  3734. }
  3735. /**
  3736. * Template Email body.
  3737. *
  3738. * @name TopNav.templateEmailBody
  3739. * @private
  3740. * @param {string} expirationDateString
  3741. * @param {bool} isBurnafterreading
  3742. */
  3743. function templateEmailBody(expirationDateString, isBurnafterreading)
  3744. {
  3745. const EOL = '\n';
  3746. const BULLET = ' - ';
  3747. let emailBody = '';
  3748. if (expirationDateString !== null || isBurnafterreading) {
  3749. emailBody += I18n._('Notice:');
  3750. emailBody += EOL;
  3751. if (expirationDateString !== null) {
  3752. emailBody += EOL;
  3753. emailBody += BULLET;
  3754. // avoid DOMPurify mess with forward slash in expirationDateString
  3755. emailBody += Helper.sprintf(
  3756. I18n._(
  3757. 'This link will expire after %s.',
  3758. '%s'
  3759. ),
  3760. expirationDateString
  3761. );
  3762. }
  3763. if (isBurnafterreading) {
  3764. emailBody += EOL;
  3765. emailBody += BULLET;
  3766. emailBody += I18n._(
  3767. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3768. );
  3769. }
  3770. emailBody += EOL;
  3771. emailBody += EOL;
  3772. }
  3773. emailBody += I18n._('Link:');
  3774. emailBody += EOL;
  3775. emailBody += $('#pasteurl').attr('href') || window.location.href; // href is tried first as it might have been shortened
  3776. return emailBody;
  3777. }
  3778. /**
  3779. * Trigger Email send.
  3780. *
  3781. * @name TopNav.triggerEmailSend
  3782. * @private
  3783. * @param {string} emailBody
  3784. */
  3785. function triggerEmailSend(emailBody)
  3786. {
  3787. window.open(
  3788. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3789. '_self',
  3790. 'noopener, noreferrer'
  3791. );
  3792. }
  3793. /**
  3794. * Send Email with current paste (URL).
  3795. *
  3796. * @name TopNav.sendEmail
  3797. * @private
  3798. * @function
  3799. * @param {Date|null} expirationDate date of expiration
  3800. * @param {bool} isBurnafterreading whether it is burn after reading
  3801. */
  3802. function sendEmail(expirationDate, isBurnafterreading)
  3803. {
  3804. const expirationDateRoundedToSecond = new Date(expirationDate);
  3805. // round down at least 30 seconds to make up for the delay of request
  3806. expirationDateRoundedToSecond.setUTCSeconds(
  3807. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3808. );
  3809. expirationDateRoundedToSecond.setUTCSeconds(0);
  3810. const $emailconfirmmodal = $('#emailconfirmmodal');
  3811. if ($emailconfirmmodal.length > 0) {
  3812. if (expirationDate !== null) {
  3813. const $emailconfirmTimezoneCurrent = $emailconfirmmodal.find('#emailconfirm-timezone-current');
  3814. const $emailconfirmTimezoneUtc = $emailconfirmmodal.find('#emailconfirm-timezone-utc');
  3815. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3816. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION ?
  3817. new bootstrap.Modal($emailconfirmmodal[0]) : null;
  3818. function sendEmailAndHideModal() {
  3819. const emailBody = templateEmailBody(
  3820. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3821. expirationDateRoundedToSecond.toLocaleString(
  3822. [], localeConfiguration
  3823. ), isBurnafterreading
  3824. );
  3825. if (bootstrap5EmailConfirmModal) {
  3826. bootstrap5EmailConfirmModal.hide();
  3827. } else {
  3828. $emailconfirmmodal.modal('hide');
  3829. }
  3830. triggerEmailSend(emailBody);
  3831. };
  3832. $emailconfirmTimezoneCurrent.off('click.sendEmailCurrentTimezone');
  3833. $emailconfirmTimezoneCurrent.on('click.sendEmailCurrentTimezone', sendEmailAndHideModal);
  3834. $emailconfirmTimezoneUtc.off('click.sendEmailUtcTimezone');
  3835. $emailconfirmTimezoneUtc.on('click.sendEmailUtcTimezone', () => {
  3836. localeConfiguration.timeZone = 'UTC';
  3837. sendEmailAndHideModal();
  3838. });
  3839. if (bootstrap5EmailConfirmModal) {
  3840. bootstrap5EmailConfirmModal.show();
  3841. } else {
  3842. $emailconfirmmodal.modal('show');
  3843. }
  3844. } else {
  3845. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3846. }
  3847. } else {
  3848. let emailBody = '';
  3849. if (expirationDate !== null) {
  3850. const expirationDateString = window.confirm(
  3851. I18n._('Recipient may become aware of your timezone, convert time to UTC?')
  3852. ) ? expirationDateRoundedToSecond.toLocaleString(
  3853. undefined,
  3854. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3855. { timeZone: 'UTC', dateStyle: 'long', timeStyle: 'long' }
  3856. ) : expirationDateRoundedToSecond.toLocaleString();
  3857. emailBody = templateEmailBody(expirationDateString, isBurnafterreading);
  3858. } else {
  3859. emailBody = templateEmailBody(null, isBurnafterreading);
  3860. }
  3861. triggerEmailSend(emailBody);
  3862. }
  3863. }
  3864. /**
  3865. * Shows all navigation elements for viewing an existing paste
  3866. *
  3867. * @name TopNav.showViewButtons
  3868. * @function
  3869. */
  3870. me.showViewButtons = function()
  3871. {
  3872. if (viewButtonsDisplayed) {
  3873. return;
  3874. }
  3875. $newButton.removeClass('hidden');
  3876. $cloneButton.removeClass('hidden');
  3877. $rawTextButton.removeClass('hidden');
  3878. $downloadTextButton.removeClass('hidden');
  3879. $qrCodeLink.removeClass('hidden');
  3880. viewButtonsDisplayed = true;
  3881. };
  3882. /**
  3883. * Hides all navigation elements for viewing an existing paste
  3884. *
  3885. * @name TopNav.hideViewButtons
  3886. * @function
  3887. */
  3888. me.hideViewButtons = function()
  3889. {
  3890. if (!viewButtonsDisplayed) {
  3891. return;
  3892. }
  3893. $cloneButton.addClass('hidden');
  3894. $newButton.addClass('hidden');
  3895. $rawTextButton.addClass('hidden');
  3896. $downloadTextButton.addClass('hidden');
  3897. $qrCodeLink.addClass('hidden');
  3898. me.hideEmailButton();
  3899. viewButtonsDisplayed = false;
  3900. };
  3901. /**
  3902. * Hides all elements belonging to existing pastes
  3903. *
  3904. * @name TopNav.hideAllButtons
  3905. * @function
  3906. */
  3907. me.hideAllButtons = function()
  3908. {
  3909. me.hideViewButtons();
  3910. me.hideCreateButtons();
  3911. };
  3912. /**
  3913. * shows all elements needed when creating a new paste
  3914. *
  3915. * @name TopNav.showCreateButtons
  3916. * @function
  3917. */
  3918. me.showCreateButtons = function()
  3919. {
  3920. if (createButtonsDisplayed) {
  3921. return;
  3922. }
  3923. $attach.removeClass('hidden');
  3924. $burnAfterReadingOption.removeClass('hidden');
  3925. $expiration.removeClass('hidden');
  3926. $formatter.removeClass('hidden');
  3927. $newButton.removeClass('hidden');
  3928. $openDiscussionOption.removeClass('hidden');
  3929. $password.removeClass('hidden');
  3930. $sendButton.removeClass('hidden');
  3931. createButtonsDisplayed = true;
  3932. };
  3933. /**
  3934. * shows all elements needed when creating a new paste
  3935. *
  3936. * @name TopNav.hideCreateButtons
  3937. * @function
  3938. */
  3939. me.hideCreateButtons = function()
  3940. {
  3941. if (!createButtonsDisplayed) {
  3942. return;
  3943. }
  3944. $newButton.addClass('hidden');
  3945. $sendButton.addClass('hidden');
  3946. $expiration.addClass('hidden');
  3947. $formatter.addClass('hidden');
  3948. $burnAfterReadingOption.addClass('hidden');
  3949. $openDiscussionOption.addClass('hidden');
  3950. $password.addClass('hidden');
  3951. $attach.addClass('hidden');
  3952. createButtonsDisplayed = false;
  3953. };
  3954. /**
  3955. * only shows the "new paste" button
  3956. *
  3957. * @name TopNav.showNewPasteButton
  3958. * @function
  3959. */
  3960. me.showNewPasteButton = function()
  3961. {
  3962. $newButton.removeClass('hidden');
  3963. };
  3964. /**
  3965. * only shows the "retry" button
  3966. *
  3967. * @name TopNav.showRetryButton
  3968. * @function
  3969. */
  3970. me.showRetryButton = function()
  3971. {
  3972. $retryButton.removeClass('hidden');
  3973. }
  3974. /**
  3975. * hides the "retry" button
  3976. *
  3977. * @name TopNav.hideRetryButton
  3978. * @function
  3979. */
  3980. me.hideRetryButton = function()
  3981. {
  3982. $retryButton.addClass('hidden');
  3983. }
  3984. /**
  3985. * show the "email" button
  3986. *
  3987. * @name TopNav.showEmailbutton
  3988. * @function
  3989. * @param {int|undefined} optionalRemainingTimeInSeconds
  3990. */
  3991. me.showEmailButton = function(optionalRemainingTimeInSeconds)
  3992. {
  3993. try {
  3994. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3995. const expirationDate = Helper.calculateExpirationDate(
  3996. new Date(),
  3997. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3998. );
  3999. const isBurnafterreading = TopNav.getBurnAfterReading();
  4000. $emailLink.removeClass('hidden');
  4001. $emailLink.off('click.sendEmail');
  4002. $emailLink.on('click.sendEmail', () => {
  4003. sendEmail(expirationDate, isBurnafterreading);
  4004. });
  4005. } catch (error) {
  4006. console.error(error);
  4007. Alert.showError('Cannot calculate expiration date.');
  4008. }
  4009. }
  4010. /**
  4011. * hide the "email" button
  4012. *
  4013. * @name TopNav.hideEmailButton
  4014. * @function
  4015. */
  4016. me.hideEmailButton = function()
  4017. {
  4018. $emailLink.addClass('hidden');
  4019. $emailLink.off('click.sendEmail');
  4020. }
  4021. /**
  4022. * only hides the clone button
  4023. *
  4024. * @name TopNav.hideCloneButton
  4025. * @function
  4026. */
  4027. me.hideCloneButton = function()
  4028. {
  4029. $cloneButton.addClass('hidden');
  4030. };
  4031. /**
  4032. * only hides the raw text button
  4033. *
  4034. * @name TopNav.hideRawButton
  4035. * @function
  4036. */
  4037. me.hideRawButton = function()
  4038. {
  4039. $rawTextButton.addClass('hidden');
  4040. };
  4041. /**
  4042. * only hides the download text button
  4043. *
  4044. * @name TopNav.hideRawButton
  4045. * @function
  4046. */
  4047. me.hideDownloadButton = function()
  4048. {
  4049. $downloadTextButton.addClass('hidden');
  4050. };
  4051. /**
  4052. * only hides the qr code button
  4053. *
  4054. * @name TopNav.hideQrCodeButton
  4055. * @function
  4056. */
  4057. me.hideQrCodeButton = function()
  4058. {
  4059. $qrCodeLink.addClass('hidden');
  4060. }
  4061. /**
  4062. * hide all irrelevant buttons when viewing burn after reading paste
  4063. *
  4064. * @name TopNav.hideBurnAfterReadingButtons
  4065. * @function
  4066. */
  4067. me.hideBurnAfterReadingButtons = function()
  4068. {
  4069. me.hideCloneButton();
  4070. me.hideQrCodeButton();
  4071. me.hideEmailButton();
  4072. }
  4073. /**
  4074. * hides the file selector in attachment
  4075. *
  4076. * @name TopNav.hideFileSelector
  4077. * @function
  4078. */
  4079. me.hideFileSelector = function()
  4080. {
  4081. $fileWrap.addClass('hidden');
  4082. };
  4083. /**
  4084. * shows the custom attachment
  4085. *
  4086. * @name TopNav.showCustomAttachment
  4087. * @function
  4088. */
  4089. me.showCustomAttachment = function()
  4090. {
  4091. $customAttachment.removeClass('hidden');
  4092. };
  4093. /**
  4094. * hides the custom attachment
  4095. *
  4096. * @name TopNav.hideCustomAttachment
  4097. * @function
  4098. */
  4099. me.hideCustomAttachment = function()
  4100. {
  4101. $customAttachment.addClass('hidden');
  4102. $fileWrap.removeClass('hidden');
  4103. };
  4104. /**
  4105. * collapses the navigation bar, only if expanded
  4106. *
  4107. * @name TopNav.collapseBar
  4108. * @function
  4109. */
  4110. me.collapseBar = function()
  4111. {
  4112. if ($('#navbar').attr('aria-expanded') === 'true') {
  4113. $('.navbar-toggle').click();
  4114. }
  4115. };
  4116. /**
  4117. * Reset the top navigation back to it's default values.
  4118. *
  4119. * @name TopNav.resetInput
  4120. * @function
  4121. */
  4122. me.resetInput = function()
  4123. {
  4124. clearAttachmentInput();
  4125. clearPasswordInput();
  4126. $burnAfterReading.prop('checked', burnAfterReadingDefault);
  4127. $openDiscussion.prop('checked', openDiscussionDefault);
  4128. if (openDiscussionDefault || !burnAfterReadingDefault) $openDiscussionOption.removeClass('buttondisabled');
  4129. if (burnAfterReadingDefault || !openDiscussionDefault) $burnAfterReadingOption.removeClass('buttondisabled');
  4130. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4131. $('#pasteExpiration>option').each(function() {
  4132. const $this = $(this);
  4133. if ($this.val() === pasteExpiration) {
  4134. $('#pasteExpirationDisplay').text($this.text());
  4135. }
  4136. });
  4137. };
  4138. /**
  4139. * returns the currently set expiration time
  4140. *
  4141. * @name TopNav.getExpiration
  4142. * @function
  4143. * @return {int}
  4144. */
  4145. me.getExpiration = function()
  4146. {
  4147. return pasteExpiration;
  4148. };
  4149. /**
  4150. * returns the currently selected file(s)
  4151. *
  4152. * @name TopNav.getFileList
  4153. * @function
  4154. * @return {FileList|null}
  4155. */
  4156. me.getFileList = function()
  4157. {
  4158. const $file = $('#file');
  4159. // if no file given, return null
  4160. if (!$file.length || !$file[0].files.length) {
  4161. return null;
  4162. }
  4163. // ensure the selected file is still accessible
  4164. if (!($file[0].files && $file[0].files[0])) {
  4165. return null;
  4166. }
  4167. return $file[0].files;
  4168. };
  4169. /**
  4170. * returns the state of the burn after reading checkbox
  4171. *
  4172. * @name TopNav.getBurnAfterReading
  4173. * @function
  4174. * @return {bool}
  4175. */
  4176. me.getBurnAfterReading = function()
  4177. {
  4178. return $burnAfterReading.prop('checked');
  4179. };
  4180. /**
  4181. * returns the state of the discussion checkbox
  4182. *
  4183. * @name TopNav.getOpenDiscussion
  4184. * @function
  4185. * @return {bool}
  4186. */
  4187. me.getOpenDiscussion = function()
  4188. {
  4189. return $openDiscussion.prop('checked');
  4190. };
  4191. /**
  4192. * returns the entered password
  4193. *
  4194. * @name TopNav.getPassword
  4195. * @function
  4196. * @return {string}
  4197. */
  4198. me.getPassword = function()
  4199. {
  4200. // when password is disabled $passwordInput.val() will return undefined
  4201. return $passwordInput.val() || '';
  4202. };
  4203. /**
  4204. * returns the element where custom attachments can be placed
  4205. *
  4206. * Used by AttachmentViewer when an attachment is cloned here.
  4207. *
  4208. * @name TopNav.getCustomAttachment
  4209. * @function
  4210. * @return {jQuery}
  4211. */
  4212. me.getCustomAttachment = function()
  4213. {
  4214. return $customAttachment;
  4215. };
  4216. /**
  4217. * Set a function to call when the retry button is clicked.
  4218. *
  4219. * @name TopNav.setRetryCallback
  4220. * @function
  4221. * @param {function} callback
  4222. */
  4223. me.setRetryCallback = function(callback)
  4224. {
  4225. retryButtonCallback = callback;
  4226. }
  4227. /**
  4228. * Highlight file upload
  4229. *
  4230. * @name TopNav.highlightFileupload
  4231. * @function
  4232. */
  4233. me.highlightFileupload = function()
  4234. {
  4235. // visually indicate file uploaded
  4236. const $attachDropdownToggle = $attach.children('.dropdown-toggle');
  4237. if ($attachDropdownToggle.attr('aria-expanded') === 'false') {
  4238. $attachDropdownToggle.click();
  4239. }
  4240. $fileWrap.addClass('highlight');
  4241. setTimeout(function () {
  4242. $fileWrap.removeClass('highlight');
  4243. }, 300);
  4244. }
  4245. /**
  4246. * set the format on bootstrap templates in dropdown programmatically
  4247. *
  4248. * @name TopNav.setFormat
  4249. * @function
  4250. */
  4251. me.setFormat = function(format)
  4252. {
  4253. $formatter.parent().find(`a[data-format="${format}"]`).click();
  4254. }
  4255. /**
  4256. * returns if attachment dropdown is readonly, not editable
  4257. *
  4258. * @name TopNav.isAttachmentReadonly
  4259. * @function
  4260. * @return {bool}
  4261. */
  4262. me.isAttachmentReadonly = function()
  4263. {
  4264. return !createButtonsDisplayed || $attach.hasClass('hidden');
  4265. }
  4266. /**
  4267. * init navigation manager
  4268. *
  4269. * preloads jQuery elements
  4270. *
  4271. * @name TopNav.init
  4272. * @function
  4273. */
  4274. me.init = function()
  4275. {
  4276. $attach = $('#attach');
  4277. $burnAfterReading = $('#burnafterreading');
  4278. $burnAfterReadingOption = $('#burnafterreadingoption');
  4279. $cloneButton = $('#clonebutton');
  4280. $customAttachment = $('#customattachment');
  4281. $expiration = $('#expiration');
  4282. $fileRemoveButton = $('#fileremovebutton');
  4283. $fileWrap = $('#filewrap');
  4284. $formatter = $('#formatter');
  4285. $newButton = $('#newbutton');
  4286. $openDiscussion = $('#opendiscussion');
  4287. $openDiscussionOption = $('#opendiscussionoption');
  4288. $password = $('#password');
  4289. $passwordInput = $('#passwordinput');
  4290. $rawTextButton = $('#rawtextbutton');
  4291. $downloadTextButton = $('#downloadtextbutton');
  4292. $retryButton = $('#retrybutton');
  4293. $sendButton = $('#sendbutton');
  4294. $qrCodeLink = $('#qrcodelink');
  4295. $emailLink = $('#emaillink');
  4296. // bootstrap template drop down
  4297. $('#language ul.dropdown-menu li a').click(setLanguage);
  4298. // page template drop down
  4299. $('#language select').change(setLanguage);
  4300. // bootstrap template drop down
  4301. $('#template ul.dropdown-menu li a').click(setTemplate);
  4302. // page template drop down
  4303. $('#template select').change(setTemplate);
  4304. // bind events
  4305. $burnAfterReading.change(changeBurnAfterReading);
  4306. $openDiscussionOption.change(changeOpenDiscussion);
  4307. $newButton.click(clickNewPaste);
  4308. $sendButton.click(PasteEncrypter.sendPaste);
  4309. $cloneButton.click(Controller.clonePaste);
  4310. $rawTextButton.click(rawText);
  4311. $downloadTextButton.click(downloadText);
  4312. $retryButton.click(clickRetryButton);
  4313. $fileRemoveButton.click(removeAttachment);
  4314. $qrCodeLink.click(displayQrCode);
  4315. // bootstrap template drop downs
  4316. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  4317. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  4318. // bootstrap5 & page drop downs
  4319. $('#pasteExpiration').on('change', function() {
  4320. pasteExpiration = Model.getExpirationDefault();
  4321. });
  4322. $('#pasteFormatter').on('change', function() {
  4323. PasteViewer.setFormat(Model.getFormatDefault());
  4324. });
  4325. // initiate default state of checkboxes
  4326. changeBurnAfterReading();
  4327. changeOpenDiscussion();
  4328. // get default values from template or fall back to set value
  4329. burnAfterReadingDefault = me.getBurnAfterReading();
  4330. openDiscussionDefault = me.getOpenDiscussion();
  4331. pasteExpiration = Model.getExpirationDefault();
  4332. createButtonsDisplayed = false;
  4333. viewButtonsDisplayed = false;
  4334. };
  4335. return me;
  4336. })(window, document);
  4337. /**
  4338. * Responsible for AJAX requests, transparently handles encryption…
  4339. *
  4340. * @name ServerInteraction
  4341. * @class
  4342. */
  4343. const ServerInteraction = (function () {
  4344. const me = {};
  4345. let successFunc = null,
  4346. failureFunc = null,
  4347. symmetricKey = null,
  4348. url,
  4349. data,
  4350. password;
  4351. /**
  4352. * public variable ('constant') for errors to prevent magic numbers
  4353. *
  4354. * @name ServerInteraction.error
  4355. * @readonly
  4356. * @enum {Object}
  4357. */
  4358. me.error = {
  4359. okay: 0,
  4360. custom: 1,
  4361. unknown: 2,
  4362. serverError: 3
  4363. };
  4364. /**
  4365. * ajaxHeaders to send in AJAX requests
  4366. *
  4367. * @name ServerInteraction.ajaxHeaders
  4368. * @private
  4369. * @readonly
  4370. * @enum {Object}
  4371. */
  4372. const ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  4373. /**
  4374. * called after successful upload
  4375. *
  4376. * @name ServerInteraction.success
  4377. * @private
  4378. * @function
  4379. * @param {int} status
  4380. * @param {int} result - optional
  4381. */
  4382. function success(status, result)
  4383. {
  4384. if (successFunc !== null) {
  4385. // add useful data to result
  4386. result.encryptionKey = symmetricKey;
  4387. successFunc(status, result);
  4388. }
  4389. }
  4390. /**
  4391. * called after a upload failure
  4392. *
  4393. * @name ServerInteraction.fail
  4394. * @private
  4395. * @function
  4396. * @param {int} status - internal code
  4397. * @param {int} result - original error code
  4398. */
  4399. function fail(status, result)
  4400. {
  4401. if (failureFunc !== null) {
  4402. failureFunc(status, result);
  4403. }
  4404. }
  4405. /**
  4406. * actually uploads the data
  4407. *
  4408. * @name ServerInteraction.run
  4409. * @function
  4410. */
  4411. me.run = function()
  4412. {
  4413. let isPost = Object.keys(data).length > 0,
  4414. ajaxParams = {
  4415. type: isPost ? 'POST' : 'GET',
  4416. url: url,
  4417. headers: ajaxHeaders,
  4418. dataType: 'json',
  4419. success: function(result) {
  4420. if (result.status === 0) {
  4421. success(0, result);
  4422. } else if (result.status === 1) {
  4423. fail(1, result);
  4424. } else {
  4425. fail(2, result);
  4426. }
  4427. }
  4428. };
  4429. if (isPost) {
  4430. ajaxParams.data = JSON.stringify(data);
  4431. }
  4432. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  4433. console.error(textStatus, errorThrown);
  4434. fail(3, jqXHR);
  4435. });
  4436. };
  4437. /**
  4438. * return currently set data, used in unit testing
  4439. *
  4440. * @name ServerInteraction.getData
  4441. * @function
  4442. */
  4443. me.getData = function()
  4444. {
  4445. return data;
  4446. };
  4447. /**
  4448. * set success function
  4449. *
  4450. * @name ServerInteraction.setUrl
  4451. * @function
  4452. * @param {function} newUrl
  4453. */
  4454. me.setUrl = function(newUrl)
  4455. {
  4456. url = newUrl;
  4457. };
  4458. /**
  4459. * sets the password to use (first value) and optionally also the
  4460. * encryption key (not recommended, it is automatically generated).
  4461. *
  4462. * Note: Call this after prepare() as prepare() resets these values.
  4463. *
  4464. * @name ServerInteraction.setCryptValues
  4465. * @function
  4466. * @param {string} newPassword
  4467. * @param {string} newKey - optional
  4468. */
  4469. me.setCryptParameters = function(newPassword, newKey)
  4470. {
  4471. password = newPassword;
  4472. if (typeof newKey !== 'undefined') {
  4473. symmetricKey = newKey;
  4474. }
  4475. };
  4476. /**
  4477. * set success function
  4478. *
  4479. * @name ServerInteraction.setSuccess
  4480. * @function
  4481. * @param {function} func
  4482. */
  4483. me.setSuccess = function(func)
  4484. {
  4485. successFunc = func;
  4486. };
  4487. /**
  4488. * set failure function
  4489. *
  4490. * @name ServerInteraction.setFailure
  4491. * @function
  4492. * @param {function} func
  4493. */
  4494. me.setFailure = function(func)
  4495. {
  4496. failureFunc = func;
  4497. };
  4498. /**
  4499. * prepares a new upload
  4500. *
  4501. * Call this when doing a new upload to reset any data from potential
  4502. * previous uploads. Must be called before any other method of this
  4503. * module.
  4504. *
  4505. * @name ServerInteraction.prepare
  4506. * @function
  4507. * @return {object}
  4508. */
  4509. me.prepare = function()
  4510. {
  4511. // entropy should already be checked!
  4512. // reset password
  4513. password = '';
  4514. // reset key, so it a new one is generated when it is used
  4515. symmetricKey = null;
  4516. // reset data
  4517. successFunc = null;
  4518. failureFunc = null;
  4519. url = Helper.baseUri();
  4520. data = {};
  4521. };
  4522. /**
  4523. * encrypts and sets the data
  4524. *
  4525. * @name ServerInteraction.setCipherMessage
  4526. * @async
  4527. * @function
  4528. * @param {object} cipherMessage
  4529. */
  4530. me.setCipherMessage = async function(cipherMessage)
  4531. {
  4532. if (
  4533. symmetricKey === null ||
  4534. (typeof symmetricKey === 'string' && symmetricKey === '')
  4535. ) {
  4536. symmetricKey = CryptTool.getSymmetricKey();
  4537. }
  4538. if (!data.hasOwnProperty('adata')) {
  4539. data['adata'] = [];
  4540. }
  4541. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4542. data['v'] = 2;
  4543. data['ct'] = cipherResult[0];
  4544. data['adata'] = cipherResult[1];
  4545. };
  4546. /**
  4547. * set the additional metadata to send unencrypted
  4548. *
  4549. * @name ServerInteraction.setUnencryptedData
  4550. * @function
  4551. * @param {string} index
  4552. * @param {mixed} element
  4553. */
  4554. me.setUnencryptedData = function(index, element)
  4555. {
  4556. data[index] = element;
  4557. };
  4558. /**
  4559. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4560. *
  4561. * @name ServerInteraction.parseUploadError
  4562. * @function
  4563. * @param {int} status
  4564. * @param {object} data
  4565. * @param {string} doThisThing - a human description of the action, which was tried
  4566. * @return {array}
  4567. */
  4568. me.parseUploadError = function(status, data, doThisThing) {
  4569. let errorArray;
  4570. switch (status) {
  4571. case me.error.custom:
  4572. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4573. break;
  4574. case me.error.unknown:
  4575. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4576. break;
  4577. case me.error.serverError:
  4578. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4579. break;
  4580. default:
  4581. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4582. break;
  4583. }
  4584. return errorArray;
  4585. };
  4586. return me;
  4587. })();
  4588. /**
  4589. * (controller) Responsible for encrypting paste and sending it to server.
  4590. *
  4591. * Does upload, encryption is done transparently by ServerInteraction.
  4592. *
  4593. * @name PasteEncrypter
  4594. * @class
  4595. */
  4596. const PasteEncrypter = (function () {
  4597. const me = {};
  4598. /**
  4599. * called after successful paste upload
  4600. *
  4601. * @name PasteEncrypter.showCreatedPaste
  4602. * @private
  4603. * @function
  4604. * @param {int} status
  4605. * @param {object} data
  4606. */
  4607. function showCreatedPaste(status, data) {
  4608. Alert.hideLoading();
  4609. Alert.hideMessages();
  4610. // show notification
  4611. const baseUri = Helper.baseUri() + '?',
  4612. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4613. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4614. PasteStatus.createPasteNotification(url, deleteUrl);
  4615. // show new URL in browser bar
  4616. history.pushState({type: 'newpaste'}, document.title, url);
  4617. TopNav.showViewButtons();
  4618. CopyToClipboard.setUrl(url);
  4619. CopyToClipboard.showKeyboardShortcutHint();
  4620. // this cannot be grouped with showViewButtons due to remaining time calculation
  4621. TopNav.showEmailButton();
  4622. TopNav.hideRawButton();
  4623. TopNav.hideDownloadButton();
  4624. Editor.hide();
  4625. // parse and show text
  4626. // (preparation already done in me.sendPaste())
  4627. PasteViewer.run();
  4628. }
  4629. /**
  4630. * called after successful comment upload
  4631. *
  4632. * @name PasteEncrypter.showUploadedComment
  4633. * @private
  4634. * @function
  4635. * @param {int} status
  4636. * @param {object} data
  4637. */
  4638. function showUploadedComment(status, data) {
  4639. // show success message
  4640. Alert.showStatus('Comment posted.');
  4641. // reload paste
  4642. Controller.refreshPaste(function () {
  4643. // highlight sent comment
  4644. DiscussionViewer.highlightComment(data.id, true);
  4645. // reset error handler
  4646. Alert.setCustomHandler(null);
  4647. });
  4648. }
  4649. /**
  4650. * send a reply in a discussion
  4651. *
  4652. * @name PasteEncrypter.sendComment
  4653. * @async
  4654. * @function
  4655. */
  4656. me.sendComment = async function()
  4657. {
  4658. Alert.hideMessages();
  4659. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4660. // UI loading state
  4661. TopNav.hideAllButtons();
  4662. Alert.showLoading('Sending comment…', 'cloud-upload');
  4663. // get data
  4664. const plainText = DiscussionViewer.getReplyMessage(),
  4665. nickname = DiscussionViewer.getReplyNickname(),
  4666. parentid = DiscussionViewer.getReplyCommentId();
  4667. // do not send if there is no data
  4668. if (plainText.length === 0) {
  4669. // revert loading status…
  4670. Alert.hideLoading();
  4671. Alert.setCustomHandler(null);
  4672. TopNav.showViewButtons();
  4673. return;
  4674. }
  4675. // prepare server interaction
  4676. ServerInteraction.prepare();
  4677. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4678. // set success/fail functions
  4679. ServerInteraction.setSuccess(showUploadedComment);
  4680. ServerInteraction.setFailure(function (status, data) {
  4681. // revert loading status…
  4682. Alert.hideLoading();
  4683. TopNav.showViewButtons();
  4684. // …show error message…
  4685. Alert.showError(
  4686. ServerInteraction.parseUploadError(status, data, 'post comment')
  4687. );
  4688. // …and reset error handler
  4689. Alert.setCustomHandler(null);
  4690. });
  4691. // fill it with unencrypted params
  4692. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4693. if (typeof parentid === 'undefined') {
  4694. // if parent id is not set, this is the top-most comment, so use
  4695. // paste id as parent, as the root element of the discussion tree
  4696. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4697. } else {
  4698. ServerInteraction.setUnencryptedData('parentid', parentid);
  4699. }
  4700. // prepare cypher message
  4701. let cipherMessage = {
  4702. 'comment': plainText
  4703. };
  4704. if (nickname.length > 0) {
  4705. cipherMessage['nickname'] = nickname;
  4706. }
  4707. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4708. ServerInteraction.run();
  4709. };
  4710. /**
  4711. * sends a new paste to server
  4712. *
  4713. * @name PasteEncrypter.sendPaste
  4714. * @async
  4715. * @function
  4716. */
  4717. me.sendPaste = async function()
  4718. {
  4719. // hide previous (error) messages
  4720. Controller.hideStatusMessages();
  4721. // UI loading state
  4722. TopNav.hideAllButtons();
  4723. Alert.showLoading('Sending paste…', 'cloud-upload');
  4724. TopNav.collapseBar();
  4725. // get data
  4726. const plainText = Editor.getText(),
  4727. format = PasteViewer.getFormat(),
  4728. // the methods may return different values if no files are attached (null, undefined or false)
  4729. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachment();
  4730. // do not send if there is no data
  4731. if (plainText.length === 0 && !files) {
  4732. // revert loading status…
  4733. Alert.hideLoading();
  4734. TopNav.showCreateButtons();
  4735. return;
  4736. }
  4737. // prepare server interaction
  4738. ServerInteraction.prepare();
  4739. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4740. // set success/fail functions
  4741. ServerInteraction.setSuccess(showCreatedPaste);
  4742. ServerInteraction.setFailure(function (status, data) {
  4743. // revert loading status…
  4744. Alert.hideLoading();
  4745. TopNav.showCreateButtons();
  4746. // show error message
  4747. Alert.showError(
  4748. ServerInteraction.parseUploadError(status, data, 'create paste')
  4749. );
  4750. });
  4751. // fill it with unencrypted submitted options
  4752. ServerInteraction.setUnencryptedData('adata', [
  4753. null, format,
  4754. TopNav.getOpenDiscussion() ? 1 : 0,
  4755. TopNav.getBurnAfterReading() ? 1 : 0
  4756. ]);
  4757. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  4758. // prepare PasteViewer for later preview
  4759. PasteViewer.setText(plainText);
  4760. PasteViewer.setFormat(format);
  4761. // prepare cypher message
  4762. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4763. cipherMessage = {
  4764. 'paste': plainText
  4765. };
  4766. if (attachmentsData.length) {
  4767. cipherMessage['attachment'] = attachmentsData;
  4768. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map((fileInfo => fileInfo.name));
  4769. } else if (AttachmentViewer.hasAttachment()) {
  4770. // fall back to cloned part
  4771. let attachments = AttachmentViewer.getAttachments();
  4772. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4773. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4774. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment) => {
  4775. // we need to retrieve data from blob if browser already parsed it in memory
  4776. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4777. Alert.showStatus(
  4778. [
  4779. 'Retrieving cloned file \'%s\' from memory...',
  4780. attachment[1]
  4781. ],
  4782. 'copy'
  4783. );
  4784. try {
  4785. const blobData = await $.ajax({
  4786. type: 'GET',
  4787. url: `${attachment}`,
  4788. processData: false,
  4789. timeout: 10000,
  4790. xhrFields: {
  4791. withCredentials: false,
  4792. responseType: 'blob'
  4793. }
  4794. });
  4795. if (blobData instanceof window.Blob) {
  4796. const fileReading = new Promise(function(resolve, reject) {
  4797. const fileReader = new FileReader();
  4798. fileReader.onload = function (event) {
  4799. resolve(event.target.result);
  4800. };
  4801. fileReader.onerror = function (error) {
  4802. reject(error);
  4803. }
  4804. fileReader.readAsDataURL(blobData);
  4805. });
  4806. return await fileReading;
  4807. } else {
  4808. const error = 'Cannot process attachment data.';
  4809. Alert.showError(error);
  4810. throw new TypeError(error);
  4811. }
  4812. } catch (error) {
  4813. Alert.showError('Cannot retrieve attachment.');
  4814. throw error;
  4815. }
  4816. }
  4817. }));
  4818. }
  4819. // encrypt message
  4820. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4821. // send data
  4822. ServerInteraction.run();
  4823. };
  4824. return me;
  4825. })();
  4826. /**
  4827. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4828. *
  4829. * Only decryption, no download.
  4830. *
  4831. * @name PasteDecrypter
  4832. * @class
  4833. */
  4834. const PasteDecrypter = (function () {
  4835. const me = {};
  4836. /**
  4837. * decrypt data or prompts for password in case of failure
  4838. *
  4839. * @name PasteDecrypter.decryptOrPromptPassword
  4840. * @private
  4841. * @async
  4842. * @function
  4843. * @param {string} key
  4844. * @param {string} password - optional, may be an empty string
  4845. * @param {string} cipherdata
  4846. * @throws {string}
  4847. * @return {false|string} false, when unsuccessful or string (decrypted data)
  4848. */
  4849. async function decryptOrPromptPassword(key, password, cipherdata)
  4850. {
  4851. // try decryption without password
  4852. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4853. // if it fails, request password
  4854. if (plaindata.length === 0 && password.length === 0) {
  4855. // show prompt
  4856. Prompt.requestPassword();
  4857. // Thus, we cannot do anything yet, we need to wait for the user
  4858. // input.
  4859. return false;
  4860. }
  4861. // if all tries failed, we can only return an error
  4862. if (plaindata.length === 0) {
  4863. return false;
  4864. }
  4865. return plaindata;
  4866. }
  4867. /**
  4868. * decrypt the actual paste text
  4869. *
  4870. * @name PasteDecrypter.decryptPaste
  4871. * @private
  4872. * @async
  4873. * @function
  4874. * @param {Paste} paste - paste data in object form
  4875. * @param {string} key
  4876. * @param {string} password
  4877. * @throws {string}
  4878. * @return {Promise}
  4879. */
  4880. async function decryptPaste(paste, key, password)
  4881. {
  4882. let pastePlain = await decryptOrPromptPassword(
  4883. key, password,
  4884. paste.getCipherData()
  4885. );
  4886. if (pastePlain === false) {
  4887. if (password.length === 0) {
  4888. throw 'waiting on user to provide a password';
  4889. } else {
  4890. Alert.hideLoading();
  4891. // reset password, so it can be re-entered
  4892. Prompt.reset();
  4893. TopNav.showRetryButton();
  4894. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4895. }
  4896. }
  4897. if (paste.v > 1) {
  4898. // version 2 paste
  4899. const pasteMessage = JSON.parse(pastePlain);
  4900. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4901. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  4902. pasteMessage.attachment.forEach((attachment, key) => {
  4903. const attachment_name = pasteMessage.attachment_name[key];
  4904. AttachmentViewer.setAttachment(attachment, attachment_name);
  4905. });
  4906. } else {
  4907. // Continue to process attachment parameters as strings to ensure backward compatibility
  4908. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4909. }
  4910. AttachmentViewer.showAttachment();
  4911. }
  4912. pastePlain = pasteMessage.paste;
  4913. } else {
  4914. // version 1 paste
  4915. if (paste.hasOwnProperty('attachment') && paste.hasOwnProperty('attachmentname')) {
  4916. Promise.all([
  4917. CryptTool.decipher(key, password, paste.attachment),
  4918. CryptTool.decipher(key, password, paste.attachmentname)
  4919. ]).then((attachment) => {
  4920. AttachmentViewer.setAttachment(attachment[0], attachment[1]);
  4921. AttachmentViewer.showAttachment();
  4922. });
  4923. }
  4924. }
  4925. PasteViewer.setFormat(paste.getFormat());
  4926. PasteViewer.setText(pastePlain);
  4927. PasteViewer.run();
  4928. }
  4929. /**
  4930. * decrypts all comments and shows them
  4931. *
  4932. * @name PasteDecrypter.decryptComments
  4933. * @private
  4934. * @async
  4935. * @function
  4936. * @param {Paste} paste - paste data in object form
  4937. * @param {string} key
  4938. * @param {string} password
  4939. * @return {Promise}
  4940. */
  4941. async function decryptComments(paste, key, password)
  4942. {
  4943. // remove potential previous discussion
  4944. DiscussionViewer.prepareNewDiscussion();
  4945. const commentDecryptionPromises = [];
  4946. // iterate over comments
  4947. for (let i = 0; i < paste.comments.length; ++i) {
  4948. const comment = new Comment(paste.comments[i]),
  4949. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4950. paste.comments[i] = comment;
  4951. if (comment.v > 1) {
  4952. // version 2 comment
  4953. commentDecryptionPromises.push(
  4954. commentPromise.then(function (commentJson) {
  4955. const commentMessage = JSON.parse(commentJson);
  4956. return [
  4957. commentMessage.comment || '',
  4958. commentMessage.nickname || ''
  4959. ];
  4960. })
  4961. );
  4962. } else {
  4963. // version 1 comment
  4964. commentDecryptionPromises.push(
  4965. Promise.all([
  4966. commentPromise,
  4967. paste.comments[i].meta.hasOwnProperty('nickname') ?
  4968. CryptTool.decipher(key, password, paste.comments[i].meta.nickname) :
  4969. Promise.resolve('')
  4970. ])
  4971. );
  4972. }
  4973. }
  4974. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4975. for (let i = 0; i < paste.comments.length; ++i) {
  4976. if (plaintexts[i][0].length === 0) {
  4977. continue;
  4978. }
  4979. DiscussionViewer.addComment(
  4980. paste.comments[i],
  4981. plaintexts[i][0],
  4982. plaintexts[i][1]
  4983. );
  4984. }
  4985. });
  4986. }
  4987. /**
  4988. * show decrypted text in the display area, including discussion (if open)
  4989. *
  4990. * @name PasteDecrypter.run
  4991. * @function
  4992. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4993. */
  4994. me.run = function(paste)
  4995. {
  4996. Alert.hideMessages();
  4997. Alert.setCustomHandler(null);
  4998. Alert.showLoading('Decrypting paste…', 'cloud-download');
  4999. if (typeof paste === 'undefined' || paste.type === 'click') {
  5000. // get cipher data and wait until it is available
  5001. Model.getPasteData(me.run);
  5002. return;
  5003. }
  5004. let key = Model.getPasteKey(),
  5005. password = Prompt.getPassword(),
  5006. decryptionPromises = [];
  5007. TopNav.setRetryCallback(function () {
  5008. TopNav.hideRetryButton();
  5009. me.run(paste);
  5010. });
  5011. // decrypt paste & attachments
  5012. decryptionPromises.push(decryptPaste(paste, key, password));
  5013. // if the discussion is opened on this paste, display it
  5014. if (paste.isDiscussionEnabled()) {
  5015. decryptionPromises.push(decryptComments(paste, key, password));
  5016. }
  5017. // shows the remaining time (until) deletion
  5018. PasteStatus.showRemainingTime(paste);
  5019. CopyToClipboard.showKeyboardShortcutHint();
  5020. Promise.all(decryptionPromises)
  5021. .then(() => {
  5022. Alert.hideLoading();
  5023. TopNav.showViewButtons();
  5024. // discourage cloning (it cannot really be prevented)
  5025. if (paste.isBurnAfterReadingEnabled()) {
  5026. TopNav.hideBurnAfterReadingButtons();
  5027. } else {
  5028. // we have to pass in remaining_time here
  5029. TopNav.showEmailButton(paste.getTimeToLive());
  5030. }
  5031. // only offer adding comments, after paste was successfully decrypted
  5032. if (paste.isDiscussionEnabled()) {
  5033. DiscussionViewer.finishDiscussion();
  5034. }
  5035. })
  5036. .catch((err) => {
  5037. // wait for the user to type in the password,
  5038. // then PasteDecrypter.run will be called again
  5039. Alert.showError(err);
  5040. });
  5041. };
  5042. return me;
  5043. })();
  5044. /**
  5045. *
  5046. * @name CopyToClipboard
  5047. * @class
  5048. */
  5049. const CopyToClipboard = (function () {
  5050. const me = {};
  5051. let copyButton,
  5052. copyLinkButton,
  5053. copyIcon,
  5054. successIcon,
  5055. shortcutHint,
  5056. url;
  5057. /**
  5058. * Handle copy to clipboard button click
  5059. *
  5060. * @name CopyToClipboard.handleCopyButtonClick
  5061. * @private
  5062. * @function
  5063. */
  5064. function handleCopyButtonClick() {
  5065. $(copyButton).click(function() {
  5066. const text = PasteViewer.getText();
  5067. saveToClipboard(text);
  5068. toggleSuccessIcon();
  5069. showAlertMessage('Paste copied to clipboard');
  5070. });
  5071. };
  5072. /**
  5073. * Handle copy link to clipboard button click
  5074. *
  5075. * @name CopyToClipboard.handleCopyLinkButtonClick
  5076. * @private
  5077. * @function
  5078. */
  5079. function handleCopyLinkButtonClick() {
  5080. $(copyLinkButton).click(function () {
  5081. saveToClipboard(url);
  5082. showAlertMessage('Link copied to clipboard');
  5083. });
  5084. }
  5085. /**
  5086. * Handle CTRL+C/CMD+C keyboard shortcut
  5087. *
  5088. * @name CopyToClipboard.handleKeyboardShortcut
  5089. * @private
  5090. * @function
  5091. */
  5092. function handleKeyboardShortcut() {
  5093. $(document).bind('copy', function () {
  5094. if (!isUserSelectedTextToCopy()) {
  5095. const text = PasteViewer.getText();
  5096. saveToClipboard(text);
  5097. showAlertMessage('Paste copied to clipboard');
  5098. }
  5099. });
  5100. };
  5101. /**
  5102. * Check if user selected some text on the page to copy it
  5103. *
  5104. * @name CopyToClipboard.isUserSelectedTextToCopy
  5105. * @private
  5106. * @function
  5107. * @returns {boolean}
  5108. */
  5109. function isUserSelectedTextToCopy() {
  5110. let text = '';
  5111. if (window.getSelection) {
  5112. text = window.getSelection().toString();
  5113. } else if (document.selection && document.selection.type != 'Control') {
  5114. text = document.selection.createRange().text;
  5115. }
  5116. return text.length > 0;
  5117. };
  5118. /**
  5119. * Save text to the clipboard
  5120. *
  5121. * @name CopyToClipboard.saveToClipboard
  5122. * @private
  5123. * @param {string} text
  5124. * @function
  5125. */
  5126. function saveToClipboard(text) {
  5127. navigator.clipboard.writeText(text);
  5128. };
  5129. /**
  5130. * Show alert message after text copy
  5131. *
  5132. * @name CopyToClipboard.showAlertMessage
  5133. * @private
  5134. * @param {string} message
  5135. * @function
  5136. */
  5137. function showAlertMessage(message) {
  5138. Alert.showStatus(message);
  5139. };
  5140. /**
  5141. * Toogle success icon after copy
  5142. *
  5143. * @name CopyToClipboard.toggleSuccessIcon
  5144. * @private
  5145. * @function
  5146. */
  5147. function toggleSuccessIcon() {
  5148. $(copyIcon).css('display', 'none');
  5149. $(successIcon).css('display', 'block');
  5150. setTimeout(function() {
  5151. $(copyIcon).css('display', 'block');
  5152. $(successIcon).css('display', 'none');
  5153. }, 1000);
  5154. };
  5155. /**
  5156. * Show keyboard shortcut hint
  5157. *
  5158. * @name CopyToClipboard.showKeyboardShortcutHint
  5159. * @function
  5160. */
  5161. me.showKeyboardShortcutHint = function () {
  5162. I18n._(
  5163. shortcutHint,
  5164. '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>'
  5165. );
  5166. };
  5167. /**
  5168. * Hide keyboard shortcut hint
  5169. *
  5170. * @name CopyToClipboard.showKeyboardShortcutHint
  5171. * @function
  5172. */
  5173. me.hideKeyboardShortcutHint = function () {
  5174. $(shortcutHint).html('');
  5175. };
  5176. /**
  5177. * Set paste url
  5178. *
  5179. * @name CopyToClipboard.setUrl
  5180. * @param {string} newUrl
  5181. * @function
  5182. */
  5183. me.setUrl = function (newUrl) {
  5184. url = newUrl;
  5185. };
  5186. /**
  5187. * Initialize
  5188. *
  5189. * @name CopyToClipboard.init
  5190. * @function
  5191. */
  5192. me.init = function() {
  5193. copyButton = $('#prettyMessageCopyBtn');
  5194. copyLinkButton = $('#copyLink');
  5195. copyIcon = $('#copyIcon');
  5196. successIcon = $('#copySuccessIcon');
  5197. shortcutHint = $('#copyShortcutHintText');
  5198. handleCopyButtonClick();
  5199. handleCopyLinkButtonClick();
  5200. handleKeyboardShortcut();
  5201. };
  5202. return me;
  5203. })();
  5204. /**
  5205. * (controller) main PrivateBin logic
  5206. *
  5207. * @name Controller
  5208. * @param {object} window
  5209. * @param {object} document
  5210. * @class
  5211. */
  5212. const Controller = (function (window, document) {
  5213. const me = {};
  5214. /**
  5215. * hides all status messages no matter which module showed them
  5216. *
  5217. * @name Controller.hideStatusMessages
  5218. * @function
  5219. */
  5220. me.hideStatusMessages = function()
  5221. {
  5222. PasteStatus.hideMessages();
  5223. Alert.hideMessages();
  5224. CopyToClipboard.hideKeyboardShortcutHint();
  5225. };
  5226. /**
  5227. * creates a new paste
  5228. *
  5229. * @name Controller.newPaste
  5230. * @function
  5231. */
  5232. me.newPaste = function()
  5233. {
  5234. // Important: This *must not* run Alert.hideMessages() as previous
  5235. // errors from viewing a paste should be shown.
  5236. TopNav.hideAllButtons();
  5237. Alert.showLoading('Preparing new paste…', 'time');
  5238. PasteStatus.hideMessages();
  5239. PasteViewer.hide();
  5240. Editor.resetInput();
  5241. Editor.show();
  5242. Editor.focusInput();
  5243. AttachmentViewer.removeAttachment();
  5244. TopNav.resetInput();
  5245. TopNav.showCreateButtons();
  5246. // newPaste could be called when user is on paste clone editing view
  5247. TopNav.hideCustomAttachment();
  5248. AttachmentViewer.clearDragAndDrop();
  5249. AttachmentViewer.removeAttachmentData();
  5250. Alert.hideLoading();
  5251. // only push new state if we are coming from a different one
  5252. if (Helper.baseUri() != window.location) {
  5253. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  5254. }
  5255. // clear discussion
  5256. DiscussionViewer.prepareNewDiscussion();
  5257. };
  5258. /**
  5259. * shows the loaded paste
  5260. *
  5261. * @name Controller.showPaste
  5262. * @function
  5263. */
  5264. me.showPaste = function()
  5265. {
  5266. try {
  5267. Model.getPasteKey();
  5268. } catch (err) {
  5269. console.error(err);
  5270. // missing decryption key (or paste ID) in URL?
  5271. if (window.location.hash.length === 0) {
  5272. 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?)');
  5273. return;
  5274. }
  5275. }
  5276. // check if we should request loading confirmation
  5277. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  5278. Prompt.requestLoadConfirmation();
  5279. return;
  5280. }
  5281. // show proper elements on screen
  5282. PasteDecrypter.run();
  5283. };
  5284. /**
  5285. * refreshes the loaded paste to show potential new data
  5286. *
  5287. * @name Controller.refreshPaste
  5288. * @function
  5289. * @param {function} callback
  5290. */
  5291. me.refreshPaste = function(callback)
  5292. {
  5293. // save window position to restore it later
  5294. const orgPosition = $(window).scrollTop();
  5295. Model.getPasteData(function (data) {
  5296. ServerInteraction.prepare();
  5297. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5298. ServerInteraction.setFailure(function (status, data) {
  5299. // revert loading status…
  5300. Alert.hideLoading();
  5301. TopNav.showViewButtons();
  5302. // show error message
  5303. Alert.showError(
  5304. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5305. );
  5306. });
  5307. ServerInteraction.setSuccess(function (status, data) {
  5308. PasteDecrypter.run(new Paste(data));
  5309. // restore position
  5310. window.scrollTo(0, orgPosition);
  5311. // NOTE: could create problems as callback may be called
  5312. // asyncronously if PasteDecrypter e.g. needs to wait for a
  5313. // password being entered
  5314. callback();
  5315. });
  5316. ServerInteraction.run();
  5317. }, false); // this false is important as it circumvents the cache
  5318. }
  5319. /**
  5320. * clone the current paste
  5321. *
  5322. * @name Controller.clonePaste
  5323. * @function
  5324. */
  5325. me.clonePaste = function()
  5326. {
  5327. TopNav.collapseBar();
  5328. TopNav.hideAllButtons();
  5329. // hide messages from previous paste
  5330. me.hideStatusMessages();
  5331. // erase the id and the key in url
  5332. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  5333. if (AttachmentViewer.hasAttachment()) {
  5334. const attachments = AttachmentViewer.getAttachments();
  5335. attachments.forEach(attachment => {
  5336. AttachmentViewer.moveAttachmentTo(
  5337. TopNav.getCustomAttachment(),
  5338. attachment,
  5339. 'Cloned: \'%s\''
  5340. );
  5341. });
  5342. TopNav.hideFileSelector();
  5343. AttachmentViewer.hideAttachment();
  5344. // NOTE: it also looks nice without removing the attachment
  5345. // but for a consistent display we remove it…
  5346. AttachmentViewer.hideAttachmentPreview();
  5347. TopNav.showCustomAttachment();
  5348. // show another status messages to make the user aware that the
  5349. // files were cloned too!
  5350. Alert.showStatus(
  5351. [
  5352. 'The cloned file \'%s\' was attached to this paste.',
  5353. attachments.map(attachment => attachment[1]).join(', '),
  5354. ],
  5355. 'copy'
  5356. );
  5357. }
  5358. Editor.setText(PasteViewer.getText());
  5359. // also clone the format
  5360. TopNav.setFormat(PasteViewer.getFormat());
  5361. PasteViewer.hide();
  5362. Editor.show();
  5363. TopNav.showCreateButtons();
  5364. // clear discussion
  5365. DiscussionViewer.prepareNewDiscussion();
  5366. };
  5367. /**
  5368. * try initializing zlib or display a warning if it fails,
  5369. * extracted from main init to allow unit testing
  5370. *
  5371. * @name Controller.initZ
  5372. * @function
  5373. */
  5374. me.initZ = function()
  5375. {
  5376. z = zlib.catch(function () {
  5377. if ($('body').data('compression') !== 'none') {
  5378. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5379. }
  5380. });
  5381. }
  5382. /**
  5383. * application start
  5384. *
  5385. * @name Controller.init
  5386. * @function
  5387. */
  5388. me.init = function()
  5389. {
  5390. // first load translations
  5391. I18n.loadTranslations();
  5392. // Add a hook to make all links open a new window
  5393. DOMPurify.addHook('afterSanitizeAttributes', function(node) {
  5394. // set all elements owning target to target=_blank
  5395. if ('target' in node && node.id !== 'pasteurl') {
  5396. node.setAttribute('target', '_blank');
  5397. }
  5398. // set non-HTML/MathML links to xlink:show=new
  5399. if (!node.hasAttribute('target')
  5400. && (node.hasAttribute('xlink:href')
  5401. || node.hasAttribute('href'))) {
  5402. node.setAttribute('xlink:show', 'new');
  5403. }
  5404. if ('rel' in node) {
  5405. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5406. }
  5407. });
  5408. // center all modals
  5409. $('.modal').on('show.bs.modal', function(e) {
  5410. $(e.target).css({
  5411. display: 'flex'
  5412. });
  5413. });
  5414. // initialize other modules/"classes"
  5415. Alert.init();
  5416. Model.init();
  5417. AttachmentViewer.init();
  5418. DiscussionViewer.init();
  5419. Editor.init();
  5420. PasteStatus.init();
  5421. PasteViewer.init();
  5422. Prompt.init();
  5423. TopNav.init();
  5424. UiHelper.init();
  5425. CopyToClipboard.init();
  5426. // check for legacy browsers before going any further
  5427. if (!Legacy.Check.getInit()) {
  5428. // Legacy check didn't complete, wait and try again
  5429. setTimeout(init, 500);
  5430. return;
  5431. }
  5432. if (!Legacy.Check.getStatus()) {
  5433. // something major is wrong, stop right away
  5434. return;
  5435. }
  5436. me.initZ();
  5437. // if delete token is passed (i.e. paste has been deleted by this
  5438. // access), add an event listener for the 'new' paste button in the alert
  5439. if (Model.hasDeleteToken()) {
  5440. $("#new-from-alert").on("click", function () {
  5441. UiHelper.reloadHome();
  5442. });
  5443. return;
  5444. }
  5445. // check whether existing paste needs to be shown
  5446. try {
  5447. Model.getPasteId();
  5448. } catch (e) {
  5449. // otherwise create a new paste
  5450. return me.newPaste();
  5451. }
  5452. // always reload on back button to invalidate cache(protect burn after read paste)
  5453. window.addEventListener('popstate', () => {
  5454. window.location.reload();
  5455. });
  5456. // display an existing paste
  5457. return me.showPaste();
  5458. }
  5459. return me;
  5460. })(window, document);
  5461. return {
  5462. Helper: Helper,
  5463. I18n: I18n,
  5464. CryptTool: CryptTool,
  5465. Model: Model,
  5466. UiHelper: UiHelper,
  5467. Alert: Alert,
  5468. PasteStatus: PasteStatus,
  5469. Prompt: Prompt,
  5470. Editor: Editor,
  5471. PasteViewer: PasteViewer,
  5472. AttachmentViewer: AttachmentViewer,
  5473. DiscussionViewer: DiscussionViewer,
  5474. TopNav: TopNav,
  5475. ServerInteraction: ServerInteraction,
  5476. PasteEncrypter: PasteEncrypter,
  5477. PasteDecrypter: PasteDecrypter,
  5478. CopyToClipboard: CopyToClipboard,
  5479. Controller: Controller
  5480. };
  5481. })(jQuery, RawDeflate);