privatebin.js 175 KB

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