privatebin.js 166 KB

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