privatebin.js 177 KB

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