privatebin.js 177 KB

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