privatebin.js 153 KB

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