privatebin.js 189 KB

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