1
0

privatebin.js 190 KB

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