privatebin.js 177 KB

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