privatebin.js 140 KB

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