privatebin.js 164 KB

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