privatebin.js 166 KB

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