privatebin.js 119 KB

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