privatebin.js 186 KB

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