privatebin.js 117 KB

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