privatebin.js 168 KB

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