privatebin.js 187 KB

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