privatebin.js 178 KB

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