privatebin.js 187 KB

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