privatebin.js 174 KB

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