privatebin.js 186 KB

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