privatebin.js 166 KB

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