privatebin.js 190 KB

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