privatebin.js 140 KB

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