privatebin.js 166 KB

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