privatebin.js 192 KB

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