privatebin.js 119 KB

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