privatebin.js 186 KB

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