privatebin.js 120 KB

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