privatebin.js 187 KB

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